1

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...

5
  • 1
    You should include the stack trace in order to help users answer faster. Commented Jun 8, 2015 at 23:37
  • Sorry, i am new at Stackoverflow. What is stack trace? :) Commented Jun 8, 2015 at 23:44
  • stackoverflow.com/help/mcve for improving your question. ) Commented Jun 8, 2015 at 23:45
  • Stacktrace: stackoverflow.com/questions/24486924/… Commented Jun 8, 2015 at 23:46
  • Here's a good SO on what Optional is stackoverflow.com/questions/24003642/… .. To me it's a design flaw in that you should never see the Optional wrapper when you're obviously trying to work with the string value of the object. Showing this in string form has no practical use in Swift and just causes problems and confusion. Commented Aug 27, 2015 at 16:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.