2015-10-05 121 views
1

我收到错误崩溃没有在互联网上没有连接时,这条线上网

fatal error: unexpectedly found nil while unwrapping an Optional value

let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary   // Line 


       self.dict = jsonData; 

       self.array1 = (self.dict.objectForKey("results") as? NSMutableArray)! 

       dispatch_async(dispatch_get_main_queue()) { 
        self.table.reloadData() 
       } 


      } catch { 

       print(error) 
      } 
     }) 
     task1.resume() 

请帮助任何帮助将apperciated

+1

可能重复的[斯威夫特2的iOS 9做抓住尝试崩溃与意外的零发现](http://stackoverflow.com/questions/32187683/swift-2-ios-9-do-catch-try-crashing-with-unexpected-nil-found) – Moritz

回答

4

出现这种情况,是因为你强迫解开的data,这始终是一个糟糕的主意,因为你不知道它nil与否。

要解决这个问题,你需要检查,如果数据是零,然后再尝试串行的JSON:

// Checking if data is nil, and unwraping it 
if let unwrappedData = data { 
    let jsonData = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: .MutableContainers) as! NSDictionary 
    // handle json here 
} 

或另一种方式:

if data == nil { 
    return 
} 
// else, data is not nil 
let jsonData = try NSJSONSerialization... 
+0

感谢您的帮助... –

+0

你不需要'unwrappedData'上的'!'。我会修复它,因为我要编辑您的帖子,以便无论如何都可以解开修改。 – JeremyP

+0

哦,我没有看到!,谢谢。 –

相关问题