我正在使用AFNetworking注册新用户,一切正常,但在下面的块中我遇到了一些问题:
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:myRequest] autorelease];
operation.completionBlock = ^ {
if ([operation hasAcceptableStatusCode]) {
NSLog(@"success");
username.backgroundColor = [UIColor yellowColor];
} else {
switch ([operation.response statusCode]) {
case 421:
{
NSLog(@"Username taken.");
username.backgroundColor = [UIColor yellowColor];
}
break;
default:
break;
}
}
};
基本上我的服务器端脚本做了一些验证并激活了HTTP状态代码(我知道421不是有效的)。这使我能够知道服务器上出了什么问题,这很有效。
我的问题是,当响应回来时,它会立即触发NSLog(@"success");
或NSLog(@"Username taken.");
,但任何其他代码会在几秒钟之后触发。
有人可以对此有所了解吗?
答案 0 :(得分:32)
这是我的问题的解决方案,这是更好的,并且快得多:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success: %@", operation.responseString);
[SVProgressHUD dismissWithSuccess:@"Sucess!" afterDelay:2];
[self saveContinue:operation.responseString];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
}
];
我希望这有助于人们。
答案 1 :(得分:0)
我的HTTP POST解决方案是
NSData *data = [self.postBody dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:self.requestUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request addValue:@"application/octet-stream" forHTTPHeaderField: @"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
NSMutableData *requestBody = [NSMutableData data];
[requestBody appendData:data];
[request setHTTPBody:requestBody];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = operation.response.statusCode;
[self requestFinished:responseObject andStatusCode:statusCode];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self requestFailed:error];
}];
[[self.requestManager operationQueue] addOperation:operation];
[AFHTTPRequestOperation batchOfRequestOperations:[NSArray arrayWithObjects:operation, nil] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
} completionBlock:^(NSArray *operations) {
}];
在这种情况下将操作管理器上的单个操作排入队列。