[英]JSON Parsing and recieved : fatal error: unexpectedly found nil while unwrapping an Optional value
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyC4BR5rZLNkeGChLr8N00BHZqBYqPdrgjg&location=43.690578,-79.342348&radius=400&types=cafe|bakery")
// 2
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
// 4
if let reposArray = json["items"] as? [NSDictionary] {
// 5
for item in reposArray {
repositories.append(Repository(json: item))
}
}
}
}
}
receiving a exc_bad_instruction error @ line 5 and not sure why, its saying im force unwrapping nil but the URL is working and i can open it in my browser without an issue and see all the JSON data 在第5行收到一个exc_bad_instruction错误,并且不确定为什么,它说我强制解开nil,但是URL在起作用,我可以在浏览器中打开它而不会出现问题,并查看所有JSON数据
Encode your URL with NSUTF8StringEncoding
: 使用NSUTF8StringEncoding
编码您的URL:
var urlstr = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyC4BR5rZLNkeGChLr8N00BHZqBYqPdrgjg&location=43.690578,-79.342348&radius=400&types=cafe|bakery"
var escapedString = urlstr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let reposURL = NSURL(string: escapedString!)
// 2
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
// 4
print(json)
if let reposArray = json["results"] as? [NSDictionary] {
// 5
for item in reposArray {
print(item)// You will get particular items
}
}
}
}
Then you will get your JSON response. 然后,您将获得JSON响应。
In the response there is no parameters like items
. 在响应中,没有像items
这样的参数。
So, after the print(json)
check the response and get the data by the parameters. 因此,在print(json)
检查响应并通过参数获取数据。
Hope this helps you. 希望这对您有所帮助。
With Swift 2 the signature for NSJSONSerialization has changed, to conform to the new error handling system. 使用Swift 2 ,NSJSONSerialization的签名已更改,以符合新的错误处理系统。 Here is the same answer as @ashish-kakkad proposed, but updated to Swift 2 这与@ ashish-kakkad提出的答案相同,但已更新为Swift 2
var urlstr = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyC4BR5rZLNkeGChLr8N00BHZqBYqPdrgjg&location=43.690578,-79.342348&radius=400&types=cafe|bakery"
var escapedString = urlstr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let reposURL = NSURL(string: escapedString!)
// 2
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
do {
if let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSDictionary {
// 4
print(json)
if let reposArray = json["results"] as? [NSDictionary] {
// 5
for item in reposArray {
print(item)// You will get particular items
}
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.