iPhone ASIHTTP - 区分 API 调用?

问题描述 投票:0回答:4

我目前有一个视图控制器,它实现了 ASIHTTP 来处理 API 调用。

我的视图控制器触发两个单独的调用。我需要能够区分

-requestFinished(ASIHTTPRequest*)
请求方法中的两个调用,这样我就可以相应地解析每个调用...

有这样做的吗?

ios objective-c asihttprequest
4个回答
9
投票

使用用户信息字段!这就是它的用途!

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.
    }
}

在此视图控制器中执行的每个不同的 ASIHTTPRequest 中为键

@"type"
处的对象设置不同的值,现在您可以在
-requestFinished:
中区分它们并适当地处理它们。

如果您真的很喜欢,您可以携带请求完成时有用的任何其他数据。例如,如果您要延迟加载图像,则可以将自己的句柄传递给要填充的 UIImageView,然后在加载图像数据后在

-requestFinished
中执行此操作!


1
投票

您可以检查传递给

request
方法的
requestFinished:(ASIHTTPRequest *)request
参数来区分这两个调用。

例如,如果两个调用具有不同的 URL,您可以检查

request.url
属性来区分两个请求。


1
投票

您可以设置在请求创建时调用的适当选择器:

[request setDelegate: self];
[request setDidFailSelector: @selector(apiCallDidFail:)];
[request setDidFinishSelector: @selector(apiCallDidFinish:)];

只需为不同的调用设置不同的选择器


0
投票

您可以检查 url/originalUrl 属性,或者您可以对其进行子类化并添加您自己的属性来指示调用方式,因为比较整数比字符串更容易/更快。

myRequest.callType = FACEBOOK_LOGIN;

我将所有调用都放在这样的枚举中:

enum calls {
FACEBOOK_LOGIN = 101,
FACEBOOK_GETWALL = 102,
...
}
© www.soinside.com 2019 - 2024. All rights reserved.