我正在尝试使用jSon编写登录系统。我可以接收并解析结果,但当我尝试使用值时,我收到了致命的错误。
我的代码:
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()
我的代码有什么问题?我不能在我的代码中使用从jSon收到的值。我对“可选”的事情感到困惑......
当我在println()中使用值时,一切都很好,但是当我使用崩溃的代码中的值时...顺便说一下它工作正常直到今天:S
这是错误:
Body: Optional({"result":1,"id":"2","name":"tt","msg":"Login successfull"})
Succes: 1
fatal error: unexpectedly found nil while unwrapping an Optional value
谢谢...