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) {
}];
この場合、Operation Managerで単一の操作を除いています。
所属していません StackOverflow