【问题标题】:iPhone ASIHTTP - Distinguishing between API calls?iPhone ASIHTTP - 区分 API 调用?
【发布时间】:2010-09-23 17:07:01
【问题描述】:

我目前有一个实现 ASIHTTP 以处理 API 调用的视图控制器。

我的视图控制器触发了 2 个单独的调用。我需要能够区分 -requestFinished(ASIHTTPRequest*)request 方法中的两个调用,因此我可以相应地解析每个调用...

有没有这样做的?

【问题讨论】:

    标签: iphone objective-c api asihttprequest


    【解决方案1】:

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

    在您在此视图控制器中执行的每个不同 ASIHTTPRequest 中,为键 @"type" 处的对象设置不同的值,您现在可以在 -requestFinished: 中区分它们并适当地处理它们。

    如果您真的很喜欢,您可以携带任何其他在请求完成时有用的数据。例如,如果您要延迟加载图像,则可以将一个句柄传递给您要填充的 UIImageView,然后在加载图像数据后在 -requestFinished 中执行此操作!

    【讨论】:

      【解决方案2】:

      您可以检查传递给您的requestFinished:(ASIHTTPRequest *)request 方法的request 参数以区分这两个调用。

      例如,如果两个调用具有不同的 URL,您可以检查 request.url 属性来区分两个请求。

      【讨论】:

        【解决方案3】:

        您可以设置应要求调用的相应选择器:

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

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

        【讨论】:

          【解决方案4】:

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

          myRequest.callType = FACEBOOK_LOGIN;
          

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

          enum calls {
          FACEBOOK_LOGIN = 101,
          FACEBOOK_GETWALL = 102,
          ...
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-20
            • 1970-01-01
            相关资源
            最近更新 更多