NSJSONSerialization:在展开可选值时意外发现 nil
NSJSONSerialization : unexpectedly found nil while unwrapping an Optional value
通常遵循代码正常工作但有时我认为,JSON returns 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 ...
读取网络响应时,应先检查是否有错误。
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();
通常遵循代码正常工作但有时我认为,JSON returns 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 ...
读取网络响应时,应先检查是否有错误。
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();