iPhone ASIHTTP - Distinguishing between API calls?

后端 未结 4 1426
故里飘歌
故里飘歌 2021-02-06 14:07

I currently have a view controller that implements ASIHTTP for handling API calls.

My view controller fires 2 separate calls. I need to be able to distinguish between t

相关标签:
4条回答
  • 2021-02-06 14:25

    Use the userInfo field! That's what it's for!

    An ASIHTTPRequest (or an ASIFormDataRequest) object has a property called .userInfo that can take an NSDictionary with anything in it you want. So I pretty much always go:

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

    Set a different value for the object at key @"type" in each different ASIHTTPRequest you do in this view controller, and you can now distinguish between them in -requestFinished: and handle each of them appropriately.

    If you're really fancy, you can carry along any other data that would be useful when the request finishes. For instance, if you're lazy-loading images, you can pass yourself a handle to the UIImageView that you want to populate, and then do that in -requestFinished after you've loaded the image data!

    0 讨论(0)
  • 2021-02-06 14:26

    You can check the url/originalUrl properties OR you can subclass it and add your own property to indicate the call how I do it because it is easier/faster to compare ints than strings.

    i.e.

    myRequest.callType = FACEBOOK_LOGIN;
    

    I have all the calls in an enum like this:

    enum calls {
    FACEBOOK_LOGIN = 101,
    FACEBOOK_GETWALL = 102,
    ...
    }
    
    0 讨论(0)
  • 2021-02-06 14:30

    You can inspect the request parameter passed to your requestFinished:(ASIHTTPRequest *)request method to differentiate between the two calls.

    For example, if the two calls have different URLs, you can inspect the request.url property to differentiate between the two requests.

    0 讨论(0)
  • 2021-02-06 14:41

    You can set the appropriate selectors which should be called at request creation:

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

    Just set different selectors for different calls

    0 讨论(0)
提交回复
热议问题