2016-10-12 3 views
0

私はGooglePlaces APIスウィフト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() 

3迅速な問題#1に更新するので、いくつかのエラーを拾っているように見える: correctedAddress、一例として、値"%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61"を返します。それにもかかわらず、何らかの理由でURL定数がゼロに戻り、クラッシュが発生します。

なぜそれがnilを返すのか分かりません。私はURLの中のcorrectedAddressを値%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61に置き換えることができるので、完全なURLは

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")となります。

問題#2: それはどの私はCould not cast value of type '__NSArrayI' (0x108bb0c08) to 'NSDictionary' (0x108bb1108).

答えて

1

のエラーはあなたの問題#問題#1の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 
} 

については、以下のコードを試してみてください取り戻すためにlet resultsでちょうどクラッシュ、してみてくださいコード

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)! 
+0

問題#2は解決されますが、問題#1は解決されません。なぜ問題2を解決するのか、なぜ私のコードがうまくいかないのか説明できますか? – luke

+0

実際、問題はあなたのコードではなく、むしろ応答を返すサーバーです。 またSwift 3では、連結やその他の目的で '\()'を使って変数を評価しているときには、最後に感嘆符を付けません。つまり、 '!'とすると何かでURLを作成しようとしますこのように: 'https://maps.googleapis.com/maps/api/geocode/json?address=Optional("%51%75%C3%A9%62%65%63%2C%20%43%61 "&6 =%6E%61%64%61")!&sensor = false "' Urlをnilとして返すので、これがissue1の理由です。これを見て、issue1コードをデバッグしようとすると、 –

+1

問題2に関連する 問題は、サーバーからの応答がすべて乱れているため、応答をキャストするためにどのタイプを使用しているか把握していなければならないということです。 興味深い質問ですが、私は遊び場を開いてプラを始めた応答タイプとwallahとying .. それは幸いにも解決されました:) 乾杯! –