通常在代码正常工作但有时我认为,JSON返回nil并遇到致命错误。如果数据为零,我该如何处理它。
我在以下行遇到EXC_BAD_INSTRUCTION错误:
let profileJsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray
感谢您的帮助。
do {
let profileJsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray
if let parseJSONArray = profileJsonArray {
self.myProfileinfo = parseJSONArray
let name: String? = self.myProfileinfo[0].valueForKey("fullname") as? String
let messsage: String? = self.myProfileinfo[0].valueForKey("message") as? String
let infourl: String! = self.myProfileinfo[0].valueForKey("thumb") as? String
let prourl: String! = self.myProfileinfo[0].valueForKey("prothumb") as? String
let email: String? = self.myProfileinfo[0].valueForKey("email") as? String ...
答案 0 :(得分:0)
从网络响应中读取时,您应该先检查是否存在错误。
例如 NSSession
:
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if error {
// Deal with error, e.g.
print(error)
}
else {
do {
// Use data or response
let profileJsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray
// ....
}
catch {
// Deal with error
}
}
})
task.resume();