gpt4 book ai didi

json - 由于使用 Google Maps API 未捕获异常 'NSRangeException' 而终止应用程序

转载 作者:行者123 更新时间:2023-11-30 10:05:31 26 4
gpt4 key购买 nike

在我的应用程序中,我在 Google Places API 自动完成的帮助下使用 Apple map 来拥有一个完整的工作系统,并且我使用 Google Maps Web API 能够通过发送纬度和经度已从 map 上的位置转换为真实坐标。

我使用以下函数来获取信息:

func getAddressForLatLng(latitude: String, longitude: String) -> Array <String> {

var location_info = [String]() // Array to Contain the returned info from Google

let url = NSURL(string: "\(base_url)latlng=\(latitude),\(longitude)&key=\(api_key)") // url + latitude + longitude + api key
let data = NSData(contentsOfURL: url!) // get the content of the url
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary // get the JSON from the url

if let result = json["results"] as? NSArray {

if let address = result[0]["address_components"] as? NSArray {

for value in 0...5 {

if let place = address[value]["short_name"]{

location_info.append(place as! String)
}
}
}
}
return location_info
}

但是当我在 iPhone 上测试该应用程序时,我不断收到以下超出范围的错误:

*** 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSCFArray objectAtIndex:]:索引 (4) 超出界限 (4)”

我测试了该阵列的所有可能的解决方案,但我一无所获。

最佳答案

请像这样编写for-in循环for value in 0...address.count-1

我已经重写了你的代码,如下所示:

 func getAddressForLatLng(latitude: String, longitude: String) -> Array <String> {

var location_info = [String]() // Array to Contain the returned info from Google

let url = NSURL(string: "\(base_url)latlng=\(latitude),\(longitude)&key=\(api_key)") // url + latitude + longitude + api key
let data = NSData(contentsOfURL: url!) // get the content of the url
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary // get the JSON from the url

if let result = json["results"] as? NSArray {

if let address = result[0]["address_components"] as? NSArray {

for value in 0...address.count-1 {

if let place = address[value]["short_name"]{

location_info.append(place as! String)
}
}
}
}

return location_info
}

关于json - 由于使用 Google Maps API 未捕获异常 'NSRangeException' 而终止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com