具有自定义NSMutableURLRequest对象的AFHTTPClient子类

时间:2012-12-14 04:14:54

标签: objective-c ios afnetworking

我的应用正在使用AFNetworking进行Twitter API访问,我通过继承AFHTTPClient创建了一个twitter api客户端:

#import "AFHTTPClient.h"

@interface TwitterAPIClient : AFHTTPClient

+ (TwitterAPIClient *)sharedClient;

@end

#import "TwitterAPIClient.h"
#import "AFJSONRequestOperation.h"

static NSString * const kAFTwitterAPIBaseURLString = @"http://api.twitter.com/1/";

@implementation TwitterAPIClient

+ (TwitterAPIClient *)sharedClient {
    static TwitterAPIClient *_sharedClient = nil;
    static dispatch_once_t TwitterAPIClientToken;
    dispatch_once(&TwitterAPIClientToken, ^{
        _sharedClient = [[TwitterAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFTwitterAPIBaseURLString]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"application/json"];

    return self;
}

@end

如果我在getPath's & postPath's上使用TwitterAPIClient,则API客户端会正确返回JSON响应,因为我将AFJSONRequestOperation注册为操作类。

但是,有时,我需要创建自定义NSMutableURLRequest请求而不使用getPath's & postPath's AFHTTPClient函数。

当我使用这些请求时,响应从客户端返回标准NSData而不是NSDictionary,因为我来自AFJSONRequestOperation

 NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/account/verify_credentials.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [self.auth authorizeRequest:request];

    AFHTTPRequestOperation* apiRequest = [[TwitterAPIClient sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {
        [self createAccount];

        self.account.username = [responseObject objectForKey:@"screen_name"];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.delegate didProfileLoaded:self.account];
        });


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error!=nil) {
            NSString* errorMessage = nil;
            NSString* errorData = [error.userInfo objectForKey:NSLocalizedRecoverySuggestionErrorKey];

            if (errorData!=nil) {
                NSError* error;
                NSDictionary* json = [NSJSONSerialization JSONObjectWithData:[errorData dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
                if (json!=nil && error==nil) {
                    NSArray* errorMeta = [json objectForKey:@"errors"];
                    if (errorMeta!=nil) {
                        errorMessage = [[errorMeta objectAtIndex:0] objectForKey:@"message"];
                    }
                } else {
                    errorMessage = errorData;
                }
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.delegate didUpdateFailed:errorMessage];
            });
        }

    }];

    [[TwitterAPIClient sharedClient] enqueueHTTPRequestOperation:apiRequest];

有没有办法可以强制将这些AFHTTPRequestOperation创建为AFJSONRequestOperation个对象?

1 个答案:

答案 0 :(得分:1)

直接创建一个AFJSONRequestOperation,如下所示:

    AFJSONRequestOperation* apiRequest = [[AFJSONRequestOperation alloc] initWithRequest:request];
[apiRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

// ....

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

// ...

}];

更多示例herehere