我目前有一个视图控制器,使用ASIHTTP处理API调用。
我的视图控制器发起了两个不同的调用。我需要能够在-requestFinished(ASIHTTPRequest*)request方法中区分这两个调用,以便可以相应地解析每个调用...
有没有什么方法可以做到这一点?
我的视图控制器发起了两个不同的调用。我需要能够在-requestFinished(ASIHTTPRequest*)request方法中区分这两个调用,以便可以相应地解析每个调用...
有没有什么方法可以做到这一点?
使用userInfo字段!这就是它的作用!
ASIHTTPRequest(或ASIFormDataRequest)对象有一个名为.userInfo的属性,可以接受一个NSDictionary,其中可以包含任何您想要的内容。所以我几乎总是这样做:
- (void) viewDidLoad { // or wherever
ASIHTTPRequest *req = [ASIHTTPRequest requestWithUrl:theUrl];
req.delegate = self;
req.userInfo = [NSDictionary dictionaryWithObject:@"initialRequest" forKey:@"type"];
[req startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
if ([[request.userInfo valueForKey:@"type"] isEqualToString:@"initialRequest"]) {
// I know it's my "initialRequest" .req and not some other one!
// In here I might parse my JSON that the server replied with,
// assemble image URLs, and request them, with a userInfo
// field containing a dictionary with @"image" for the @"type", for instance.
}
}
@"type"
的对象设置不同的值,这样你就可以在-requestFinished:
中区分它们并适当地处理每一个请求。-requestFinished
中执行该操作!您可以设置在请求创建时应调用的适当选择器:
[request setDelegate: self];
[request setDidFailSelector: @selector(apiCallDidFail:)];
[request setDidFinishSelector: @selector(apiCallDidFinish:)];
只需为不同的调用设置不同的选择器
requestFinished:(ASIHTTPRequest *)request
方法的request
参数,以区分这两个调用。request.url
属性来区分这两个请求。您可以检查url/originalUrl属性,或者可以对其进行子类化并添加自己的属性以指示调用如何执行,因为比较整数比字符串更容易/更快。
例如:
myRequest.callType = FACEBOOK_LOGIN;
我把所有的调用都放在一个枚举里,就像这样:
enum calls {
FACEBOOK_LOGIN = 101,
FACEBOOK_GETWALL = 102,
...
}