Search code examples
swiftnsarrayxcode6.1.1

Error : Command failed due to signal : Segmentation fault: 11


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
        }
    })
}

Solution

  • There are a few problems with your code:

    1. Your code does not even compile. Segfault is coming from the compiler, not at runtime

    2. You should cast the result from JSONObjectWithData as NSDictionary, not assign to a variable of type AnyObject!

    3. Should use if to check if the casting works

    4. 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)
    
            }
    
        }
    })