2016-04-22 56 views
0

我是新來的iOS和飛速發展之後崩潰。我最近將alamofire lib遷移到了V3.0,它產生了代碼錯誤。我設法解決所有問題。但是還有一個最後的問題。我有一個名爲Webservices的類用於調用Web服務。它有一個名爲postCustomLogin的方法。在我viewcontrollers的一個我打電話吧,當我運行的應用程序崩潰,在這一行:NSJSONSerialization.JSONObjectWithData導致應用alamofire遷移

errorCode = try NSJSONSerialization.JSONObjectWithData(result.value as! NSData , options:NSJSONReadingOptions.AllowFragments) as! NSString 

下面是函數的定義:

class func postCustomLogin(email: String, password: String, completionHandler: (Result<AnyObject, NSError>) -> Void) { 
Alamofire.request(.POST, baseURL + "CustomLogin", parameters: ["email": email, "password": password]) 
     .validate() 
     .responseJSON {(response) in 
      if (response.result.isSuccess) { 
       if let jsonDict = response.result.value as? NSDictionary { 
        User.createEntityWithDictionnary(jsonDict) 
        //Save     NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait() 
       } 
      } 
      completionHandler(response.result) 
    } 
} 

這裏是我」 m調用功能:

Webservices.postCustomLogin(user!, password: password!, completionHandler: { (result) in 
      do { 
       if (result.value != nil) 
       { 
        errorCode = try NSJSONSerialization.JSONObjectWithData(result.value as! NSData , options:NSJSONReadingOptions.AllowFragments) as! NSString//crash 

回答

1

您正在強制拆封您的optionals。如果您result.value不是NSDatatry NSJSONSerialization.JSONObjectWithData(result.value as! NSData , options:NSJSONReadingOptions.AllowFragments) as! NSString//crash不是NSString您的應用程序崩潰。與此代碼對安全試着解開:

if let resultData = result.value as? NSData{ 
    if let anErrorCode = try NSJSONSerialization.JSONObjectWithData(resultData , options:NSJSONReadingOptions.AllowFragments) as? NSString 
    error = anErrorCode 
    .... 
    .... 
} 
相關問題