0
我的應用程序是使用AFNetworking
Twitter的API訪問,我已經通過繼承AFHTTPClient
創建一個Twitter的API客戶端:定製NSMutableURLRequest AFHTTPClient子類對象
#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
如果我在TwitterAPIClient
使用getPath's & postPath's
,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
對象?
對不起,我發佈了一個答案,但誤解了它,刪除了。 – allaire