我需要在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 –