我需要在Swift 3中通过PHP从mySQL获取我的GPS位置。我试着编写获取数据的代码,但它仍然不起作用,你能告诉我吗?
PHP的JSON数据:
[{" ID":" 3752""纬度":" 11.2222""经度" :" 111.2222""速度":" 0.000000""伏":" 3.97",& #34;百分比":" 87.000000","日期":" 2017-03-07 22:53:32"}]
Swift 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)")
}
}
错误消息
无法转换类型&#39; __ NSSingleObjectArrayI&#39;的值(0x1065fad60)来 &#39;的NSDictionary&#39; (0x1065fb288)。
答案 0 :(得分:0)
尝试将json对象直接转换为Swift表示,以获得更多的Swifty&#39;访问基础数据。因此,您不需要与NSNumber等一起大惊小怪。
guard let json = JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: String]] else { return }
guard json.count > 0 else { return }
guard let lattitude = json[0]["lattitude"] else { return }
print("Lattitude received: \(lattitude)")
如果你不确定你是否有一个[String: String]
对象数组,你可以用强制转换中的[String: Any]
替换它,那么你需要做的就是检查一下在读取格子时可选择演员。您可以添加一个链式可选项,然后检查isEmpty
以检查它是否是您想要的格值或出错的地方。
我也建议你几乎不要在你的代码中使用!
,尝试更多地依赖可选的链接和保护语句。
注意:单个线路保护语句并不是非常详细,可能会使调试应用程序变得非常困难。考虑在guard语句的主体中抛出错误或进行一些调试打印。