【发布时间】:2015-10-02 04:26:06
【问题描述】:
大家好,这些天我正在学习 swift 教程,目前正在研究如何使用 swift 使用 php 和 mysql。无论如何,我设法将数据保存在 mysql 数据库中。不知何故,我可以得到一个带有返回消息的 json 对象,但是当我要使用“NSJSONSerialization.JSONObjectWithData”来获取实际数据时,应用程序会崩溃。
这是目前为止的代码 sn-p :
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data , response, error ) -> Void in
let dataContent = data! as NSData
dispatch_async(dispatch_get_main_queue()){
if error != nil{
self.displayAlertMessage(error!.localizedDescription);
return
}
print("error + \(error)" )
print(data) // actually up to this level the code works
do {
//let json = try NSJSONSerialization.JSONObjectWithData(data! , options: .MutableContainers ) as? NSDictionary;
// here thread gonna crash and shows : "Thread 1: breakpoint 1.1" message with green line
var json = try NSJSONSerialization.JSONObjectWithData(dataContent , options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(json)
if let parseJSON:NSDictionary = json{
let userId = parseJSON["userId"] as? String
if userId != nil{
var myAlert = UIAlertController(title: "Alert", message: "Registration Successful", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){(action) in
self.dismissViewControllerAnimated(true, completion: nil )
}
}else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil ){
self.displayAlertMessage(errorMessage!)
}
}
}
} catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
}
}).resume()
}
我停留在“尝试 NSJSONSerialization.JSONObjectWithData”这一行。谁能帮我解决这个问题?
感谢大家的大力帮助
【问题讨论】:
标签: json multithreading serialization crash swift2