Hedi Naily Hedi Naily - 7 months ago 26
Swift Question

NSJSONSerialization.JSONObjectWithData causing app to crash after alamofire migration

I'm new to iOS and swift development. I recently migrated alamofire lib to V3.0 which generated code errors. I managed to solve them all. However there is a last problem. I have a class named Webservices used to invoke web services. It has a method called postCustomLogin. In one of my viewcontrollers I'm calling it, when I run the app it crashes at this line :

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


Here is the definition of the function :

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)
}
}


and here is where I'm calling the function :

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

Answer

You are forcing the unwrap of your optionals. If your result.value isn't a NSData or try NSJSONSerialization.JSONObjectWithData(result.value as! NSData , options:NSJSONReadingOptions.AllowFragments ) as! NSString//crash isn't a NSString your app crash. Try with this code for safely unwrap:

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