스위프트 3의 PHP로 mySQL에서 GPS 위치를 가져와야합니다. 데이터를 가져 오기위한 코드를 작성하려고했지만 여전히 작동하지 않습니다. 조언 해 주시겠습니까? PHP에서Swift 3에서 JSON 데이터를 구문 분석하는 방법은 무엇입니까?
JSON 데이터 :
[{ "ID": "3752", "위도": "11.2222", "경도": "111.2222", "속도": "0.000000", " 볼트 ":"3.97 ","비율 ":"87.000000 ","날짜 ":"2017년 3월 7일 22시 53분 32초 "}]
스위프트 3 코드 :
import UIKit
//-------- import google map library --------//
import GoogleMaps
import GooglePlaces
class ViewController: UIViewController , GMSMapViewDelegate {
var placesClient: GMSPlacesClient!
override func viewDidLoad() {
super.viewDidLoad()
var abc : String = String()
//-------- Google key for ios --------//
GMSServices.provideAPIKey("XXXXXXXXXX")
GMSPlacesClient.provideAPIKey("XXXXXXXXX")
//--------set URL --------//
let myUrl = URL(string: "http://www.myweb/service.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of latiutde
let latitude= parseJSON["latitude"] as? String //<---- Here , which i need latitude value
print("latitude = \(latitude)")
}
} catch {
print(error)
}
}
task.resume()
}
코드를 작성하려고했지만 디버그 출력에 오류가 표시됩니다.
let responseString = String(data: data, encoding: .utf8)
let str = String(data: data, encoding: .utf8)
let data2 = str?.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data2!, options: []) as! [String: AnyObject]
if let names = json["latitude"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
오류 메시지 유형의 값을 캐스팅 할 수 없습니다 '__NSSingleObjectArrayI'(0x1065fad60) 'NSDictionary에'(0x1065fb288) 에.
"작동하지 않음"을 정의하십시오. – rmaddy
기타 : http://stackoverflow.com/q/38155436/2415822 – JAL
a l a m o f i r e –