2016-04-22 41 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 
    .... 
    .... 
} 
相关问题