I am trying to get an array from dictionary, but I am getting an error for below line
self.items = self.dataDictionary["geoNames"] as NSArray
Complete code is as below
var dataDictionary: AnyObject!
var items: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: "http://api.geonames.org/countryInfoJSON?username=temp")
var urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue:NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (data.length > 0 && error == nil){
self.dataDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
println(self.dataDictionary)
self.items = self.dataDictionary["geoNames"] as NSArray
}
})
}
There are a few problems with your code:
Your code does not even compile. Segfault is coming from the compiler, not at runtime
You should cast the result from JSONObjectWithData
as
NSDictionary
, not assign to a variable of type AnyObject!
Should use if
to check if the casting works
The dictionary key is wrong. It is geonames
(all lowercase)
Here is the functional code:
var url = NSURL(string: "http://api.geonames.org/countryInfoJSON?username=temp")
var urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue:NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (data.length > 0 && error == nil){
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
let dataDictionary = jsonObject["geonames"]
println(dataDictionary)
}
}
})