2017-03-07 38 views
-2

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

+0

定義「不起作用」。 – rmaddy

+0

另外:http://stackoverflow.com/q/38155436/2415822 – JAL

+1

a l a m o f i r e –

回答

0

嘗試將json對象直接轉換爲Swift表示,以便更底層數據的「Swifty」訪問。所以,你不必大驚小怪周圍的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]替換它,那麼你需要do是在讀取格子時用可選的cast來檢查類型。您可以添加一個鏈接選項,然後檢查isEmpty以檢查其是否需要或者出錯。

我也建議幾乎不會在代碼中使用!,嘗試更多地依賴可選的鏈接和保護語句。

Guard statement introduction

注:單行後衛語句不是很詳細,可能使其很難調試應用程序。考慮拋出錯誤或在guard語句的主體中進行更多的調試打印。