2015-10-05 83 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

哦,我沒有看到!,謝謝。 –