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

mstfa
  • 11
  • 2
  • 1
    You should include the stack trace in order to help users answer faster. – goncalotomas Jun 08 '15 at 23:37
  • Sorry, i am new at Stackoverflow. What is stack trace? :) – mstfa Jun 08 '15 at 23:44
  • http://stackoverflow.com/help/mcve for improving your question. ) – Nick Volynkin Jun 08 '15 at 23:45
  • Stacktrace: http://stackoverflow.com/questions/24486924/how-can-i-get-stack-trace-error-in-swift – Nick Volynkin Jun 08 '15 at 23:46
  • Here's a good SO on what Optional is http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift .. 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. – Wedge Martin Aug 27 '15 at 16:52

0 Answers0