Convert mutableCopy to Swift

I found this guide to get the HTTP body, because it contains an error message with JSON formatting with AFNetworking 2. The guide is in Objective-C and I try my best to turn it into Swift.

Here is the code I'm trying to convert to Swift:

- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error { if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { if (*error != nil) { NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy]; NSError *jsonError; // parse to json id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; // store the value in userInfo if JSON has no error if (jsonError == nil) userInfo[JSONResponseSerializerWithDataKey] = json; NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo]; (*error) = newError; } return (nil); } return ([super responseObjectForResponse:response data:data error:error]); } 

More specifically, this part has a problem:

 NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy]; 

This is my current code:

 class JSONResponseSerializerWithData: AFJSONResponseSerializer { let JSONResponseSerializerWithDataKey: NSString = "JSONResponseSerializerWithDataKey" override func responseObjectForResponse(response: NSURLResponse!, data: NSData!, error: NSErrorPointer) -> AnyObject? { if(!self.validateResponse(response as NSHTTPURLResponse, data: data, error: error)) { if(error != nil) { // The question..... var jsonError: NSError // parse to json // Missing some returns with AnyObejct... } return nil } } } 

How to convert this string to Swift? I am new to Swift / Objective-C, so there may be a simple solution for it, but I have not been able to find it yet.

+6
source share
2 answers

I found the same guide that describes how to parse the error message in AFNetworking 2, and here is my implementation in Swift:

 override func responseObjectForResponse(response: NSURLResponse!, data: NSData!, error: NSErrorPointer) -> AnyObject! { if !self.validateResponse(response as! NSHTTPURLResponse, data: data, error: error) { if error != nil { var userInfo = error.memory!.userInfo! var jsonError:NSError? let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &jsonError) userInfo[JSONResponseSerializerWithDataKey] = json; error.memory = NSError(domain: error.memory!.domain, code: error.memory!.code, userInfo: userInfo) } return nil } return super.responseObjectForResponse(response, data: data, error: error) } 

Hope this helps someone.

+1
source

I think this should do the trick:

 var userInfo = error.userInfo 
+3
source

Source: https://habr.com/ru/post/984792/


All Articles