luke luke - 1 month ago 39
iOS Question

GooglePlaces API Swift 3 Issue

I seem to have picked up a few errors since updating to swift 3

// Issue #1
let correctedAddress:String! = self.searchResults![(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
print(correctedAddress)
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false")

let task = URLSession.shared.dataTask(with: url!) {
data, response, error in

do {
if data != nil{
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary

// Issue #2
let results = dic["results"] as! [String: Any]
let geometry = results["geometry"] as! [String: Any]
let location = geometry["location"] as! [String: Any]

let lat = location["lat"] as! Double
let lon = location["lng"] as! Double

self.delegate.locateWithLongitude(lon, andLatitude: lat)
}
}
catch {
print("Error")
}
}
task.resume()


issue #1:
correctedAddress, as an example, returns value
"%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61"
. Nevertheless, for some reason the url constant returns nil and causes a crash.

I don't understand why it returns nil. I can replace
correctedAddress
inside the url with the value
%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61
so the full url is

let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61&sensor=false")
and it works fine.

issue #2:
It crashes just at
let results
to which i get back the error of
Could not cast value of type '__NSArrayI' (0x108bb0c08) to 'NSDictionary' (0x108bb1108).

Answer

Try the below code for your Issue#2

let results = dic["results"] as! NSArray
for result in results {
    let strObj = result as! NSDictionary
    let geometry = strObj["geometry"] as! NSDictionary
    let location = geometry["location"] as! NSDictionary
    let lat = location["lat"] as! NSNumber
    let lon = location["lng"] as! NSNumber
}

For issue#1, try the below code

let valueAtIndex = self.searchResults![(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
guard let correctedAddress = valueAtIndex else { return }
let adrString:String = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false"
let url:URL = URL(string: adrString)!