-2

I need to get my GPS location from mySQL by PHP in Swift 3. I tried to write the code for get data but it still not work, could you advise me?

JSON Data from PHP:

[{"id":"3752","latitude":"11.2222","longitude":"111.2222","Speed":"0.000000","Volt":"3.97","Percent":"87.000000","Dates":"2017-03-07 22:53:32"}]

Swift 3 code:

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()     

}

I tried to write the code but it show the errors on debug output

    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)")
    }            

}

Error message

Could not cast value of type '__NSSingleObjectArrayI' (0x1065fad60) to 'NSDictionary' (0x1065fb288).

1 Answers1

0

Try casting the json object to a Swift representation directly for a more 'Swifty' access of the underlying data. So you don't need to fuss around with NSNumber etc.

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)")

If you are not sure you'll have a [String: String] object array, you can replace it with a [String: Any] in the cast, then all you need to do is check the type with an optional cast in reading the lattitude. You could add a chained optional then checking for isEmpty to check whether its the lattitude value you want or something went wrong.

I would also advice to pretty much never use ! in your code, try to rely more on optional chaining and guard statements.

Guard statement introduction

Note: a single line guard statement isn't very verbose and might make it very difficult to debug your application. Consider throwing errors or some more debug printing in the body of the guard statement.

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52