afnetworking,afhttprequeStoperation完成块慢速对消防代码
-
25-10-2019 - |
题
我正在使用注册新用户的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.");
马上,但其他任何代码在相当多秒后发射。
谁能对此有任何启示?
解决方案
这是解决我问题的解决方案,这要好得多,而且地狱更快:
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);
}
];
我希望这对人们有所帮助。
其他提示
我对HTTP帖子的解决方案是
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) {
}];
在这种情况下,该操作经理上的单个操作都在于。
不隶属于 StackOverflow