2016-04-25 58 views
0

我試圖從Swift 1到if let jsonData Array = try NSJSONSerialization...行2,因爲它最初給我一個錯誤「調用額外的參數」錯誤「所以我在NSJSONSerialization之前添加了」嘗試「,但現在它說」無效轉換類型'(NSData!, NSError!) throws ->()' to non-throwing function type '(NSData!, NSError!) -> Void'類型的投擲功能。我認爲錯誤處理不正確,但我不知道該怎麼做。這裏的代碼從類型'(NSData!,NSError!)拋出函數無效轉換拋出 - >()'到非拋出函數類型'(NSData !, NSError!) - >虛線'

httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in 
     if error != nil { 
      let errorMessage = self.httpHelper.getErrorMessage(error) 
      let errorAlert = UIAlertView(title:"Error", message:errorMessage as String, delegate:nil, cancelButtonTitle:"Ok") 
      errorAlert.show() 

      return 
     } 

     var error: NSError? 

     // let jsonDataDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as! NSDictionary 
     // let jsonDataDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary 

     if let jsonDataArray = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSArray! { 
      //load collection view with selfies 
      if jsonDataArray != nil { 
       for imageDataDict in jsonDataArray { 
        var selfieImgObj = SelfieImage() 

        selfieImgObj.imageTitle = imageDataDict.valueForKey("title") as! String 
        selfieImgObj.imageId = imageDataDict.valueForKey("random_id") as! String 
        selfieImgObj.imageThumbnailURL = imageDataDict.valueForKey("image_url") as! String 

        self.dataArray.append(selfieImgObj) 
       } 

       self.collectionView?.reloadData() 
      } 
     } 
     }) 
    } 
+0

出於某種原因,它沒有顯示前幾行代碼爲。如果錯誤!= nil {error} = self.httpHelper.getErrorMessage(error) let errorAlert = UIAlertView (標題:「錯誤」,消息:errorMessage爲字符串,委託:無,cancelButtonTitle:「確定」) errorAlert.show() – Nick

回答

0

首先,你應該包裝,在一個do-try-catch循環調用throws任何功能。其次,安全地拆禮物jsonArray作爲雨燕陣列,而不是試圖迫使其轉換爲NSArray

do { 
    if let jsonArray = try NSJSONSerialization.JSONObjectWithData(NSData(), options: .AllowFragments) as? [AnyObject] { 
     // unarchived data is an array 
    } 
} catch { 
    print(error) 
} 
相關問題