我的应用正在使用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
个对象?
答案 0 :(得分:1)
直接创建一个AFJSONRequestOperation,如下所示:
AFJSONRequestOperation* apiRequest = [[AFJSONRequestOperation alloc] initWithRequest:request];
[apiRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// ....
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// ...
}];