jSon result optional value error

168 views Asked by At

I am trying to code a login system with jSon. I can receive and parse the results but when i am trying to use values i am receiving fatal errors.

My code:

var request = NSMutableURLRequest(URL: NSURL(string: "http://www.somedomain.com/api/login.php")!)
        var session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        var params:NSDictionary = ["e":"\(email)", "p":"\(passwd)"]


        var err: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Body: \(strData)")
            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary


            if(err != nil) {
                println(err!.localizedDescription)
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: '\(jsonStr)'")
            }
            else {
                if let parseJSON = json {
                    var success = parseJSON["result"] as? Int
                    var msg = parseJSON["msg"] as? String
                    println("Succes: \(success!)") // This works fine i can receive the success variable from json 

                    if success! == 1 {  // this line throws error as "fatal error: unexpectedly found nil while unwrapping an Optional value"
                        // Do something...
                    } else {

                        // Do something...     
                        }
                    }


                } else {
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: \(jsonStr)")
                }
            }
        })

        task.resume()

What's the problem with my code? I can not use the values that i received from jSon in my code. I am really confused with the "Optional" thing...

When i use values in println() everything is fine, but when i use the values in code that crashes... By the way it was working fine until today :S

This is the error:

Body: Optional({"result":1,"id":"2","name":"tt","msg":"Login successfull"})
Succes: 1
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks...

0

There are 0 answers