luke luke - 7 months ago 126
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)
let url = URL(string: "\(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 {

issue #1:
correctedAddress, as an example, returns value
. Nevertheless, for some reason the url constant returns nil and causes a crash.

I don't understand why it returns nil. I can replace
inside the url with the value
so the full url is

let url = NSURL(string: "")
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).


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 = "\(correctedAddress)&sensor=false"
let url:URL = URL(string: adrString)!