我需要在Swift 3中通過PHP從mySQL獲取我的GPS位置。我試圖編寫獲取數據的代碼,但它仍然不起作用,您能否告訴我?如何解析Swift 3中的JSON數據?
JSON從PHP數據:
[{ 「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 –