我通常最终使用 ASIFormDataRequest 并使用 NSThread 来分离一个新线程以及调用。然后我让它在完成后调用我自己的委托/协议:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"some_url"]];
[request setUseKeychainPersistence:YES];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
for (NSString *key in dictionary) {
[request setPostValue:[dictionary objectForKey:key] forKey:key];
}
[request startSynchronous];
if([request responseStatusCode] == 200)
{
NSString *response = [NSString stringWithFormat:@"%@", [request responseString]];
if ([self _isValidDelegateForSelector:@selector(requestSucceeded)]) {
[_delegate requestSucceeded];
}
if ([self _isValidDelegateForSelector:@selector(itemAdded:)]) {
[_delegate itemAdded:[response JSONValue]];
}
}
else {
if ([self _isValidDelegateForSelector:@selector(requestFailedWithError:)])
NSLog(@"%@", [request debugDescription]);
[_delegate requestFailedWithError:[request error]];
}
这一切都是在我自己的“API”对象中完成的,该对象包含对 Web 服务的所有调用,因此我调用startSynchronous
而不是异步调用,因为我无论如何都在不同的线程中处理它。