将mutableCopy转换为Swift

时间:2015-04-07 14:17:04

标签: swift afnetworking

我发现这个guide收到一个HTTP Body,其中包含一个带有AFNetworking 2的JSON格式错误消息。该指南是在Objective-C中,我正在尽我所能将其转换为Swift。

这是我试图转换为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]);
}

更具体的是,这部分存在问题:

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

这是我目前的代码:

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

如何将此行转换为Swift? 我对Swift / Objective-C语言很新,所以可能有一个简单的解决方案,但我还没有找到它。

2 个答案:

答案 0 :(得分:3)

我认为这应该可以解决问题:

var userInfo = error.userInfo

答案 1 :(得分:1)

我找到了描述如何在AFNetworking 2中解析错误消息的相同指南,这是我在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)
    }

希望这会对某人有所帮助。