使用AFJSONRequestOperation时遇到1个问题。我的API客户端如下
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
@interface MyAPIClient : AFHTTPClient
+ (MyAPIClient *)sharedAPIClient;
@end
// .m file
#import "MyAPIClient.h"
@implementation MyAPIClient
+ (MyAPIClient *)sharedAPIClient {
static MyAPIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBASE_URL]];
});
return sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:CONTENT_TYPE_FIELD value:CONTENT_TYPE_JSON_VALUE];
self.parameterEncoding = AFJSONParameterEncoding;
return self;
}
@end
现在,当我使用以下代码请求时,它返回“null”响应
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:userName,@"email",password,@"password",nil];
NSMutableURLRequest *request = [[MyAPIClient sharedAPIClient] requestWithMethod:@"POST" path:@"login" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSDictionary *dictResponse = (NSDictionary*)JSON;
DLog(@"Login Success JSON: %@",JSON);
if (block) {
block(YES,nil);
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
DLog(@"Login Error:- %@",error);
if (block) {
block(NO,error);
}
}];
[operation start];
但是当我使用AFHTTPRequestOperation时,它会重新输入正确的输出并记录下使用过的信息
NSURL *loginUrl = [NSURL URLWithString:kBASE_URL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:loginUrl];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userName,@"email",password,@"password",nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"login" parameters:params];
//Notice the different method here!
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"Raw data Response: %@", responseObject);
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(@"Converted JSON : %@", jsonArray);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error: %@", error);
}];
//Enqueue it instead of just starting it.
[httpClient enqueueHTTPRequestOperation:operation];
我的服务器返回JSON响应。 上面的代码有什么问题?为什么AFJSONRequestOperation在返回时返回null响应 AFHTTPRequestOperation会给我正确的回复吗?任何形式的帮助表示赞赏。提前致谢