Keshav
Keshav

Reputation: 1133

parsing JSON in swift throws 'fatal error: unexpectedly found nil while unwrapping an Optional value'

I am trying to fetch the json object but I am not able to get here is my code

 func loadShots(completion : ((AnyObject) -> Void)!) {

        var urlString = "http://ip.jsontest.com/";
        let session = NSURLSession.sharedSession()
        let shotsUrl = NSURL(string : urlString)

        var task = session.dataTaskWithURL(shotsUrl!){

        (data,response,error) -> Void in
        if error != nil {
        println(error.localizedDescription)
        }else{

           // var error :NSError?
            var shotsData = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: nil) as NSArray //throws error here

            var shots = [IpTest]()

            for shot in shotsData{
            let shot = IpTest(data: shot as NSDictionary)
            shots.append(shot)

            }
             let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
            dispatch_async(dispatch_get_global_queue(priority,0)){
                dispatch_async(dispatch_get_main_queue()){
                    completion(shots)
                }
            }

        }
        }
        task.resume()
    }

when I am typing "do shots" in console, it gives 'error: _regexp-down [n]'. Any suggestions what i am doing wrong?

Here is my class declaration:

class IpTest {
    var ip : String?
    init(data : NSDictionary){

        let ip  = data["ip"] as String
        self.ip = getStringFromJson(data,key: "ip")

    }


    func getStringFromJson(data: NSDictionary,key : String) -> String {

        let info : AnyObject? = data[key]

        if let info = data[key] as? String{
            return info
        }
        return ""
    }
}

Upvotes: 2

Views: 493

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Your JSON response is a Dictionary, but you cast the result of NSJSONSerialization to an NSArray.

If you change shotsData declaration like this:

var shotsData = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: nil) as! [String:AnyObject]

then shotsData is a Swift Dictionary with a String as a key, shadowing the JSON format you received.

Change the init of your IpTest class accordingly:

init(data: [String:AnyObject])

Then you can initialize your object:

let shot = IpTest(data: shotsData)

And append the object to your array:

var shots = [IpTest]()
shots.append(shot)

Upvotes: 2

Related Questions