在有人发送线程告诉我这不是最佳做法之前,有充分的理由在这种情况下我没有使用异步方法。
我正在尝试强制我的AFNetworking库以某种方法调用的同步模式运行(已被分解)。
这是我的(黑客)片段:
NSURL *url = [NSURL URLWithString:_apiBaseUrl];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:url];
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];
NSDictionary *requestDict = [NSDictionary dictionaryWithObjects:@[@"2.0", path, params, [NSNumber numberWithInt:(int)[[NSDate date] timeIntervalSince1970]]] forKeys:@[@"jsonrpc", @"method", @"params", @"id"]];
NSString *requestBody = [requestDict JSONString];
NSLog(@"requestBody: %@", requestBody);
// Set the request body
[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// Do something with the success (never reached)
successBlock(request, response, JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
failureBlock(request, response, error, JSON);
}];
if (queue == 1) {
[self.operationArray addObject:operation];
}
else {
[operation waitUntilFinished];
successBlock(nil, nil, nil);
//[operation start];
}
当运行该方法并且队列参数强制该方法为waitUntilFinished时,永远不会到达成功块,也不是下一行。如果我使用start方法,它可以正常工作。