Timer vs ASIHTTPRequest - find optimal solution

2019-06-09 19:35发布

问题:

The code is shown as below, I have a button once you click it activates timer and timer calls method every 4sec. However, sometimes 4 sec is not enough for server to return the data. However, increasing the timer value is not also good solution if server returns data in 1 sec and would not good for user to wait longer. I do not know what is best/optimal solution in this case.

-(IBAction)play:(id)sender{
    timer=[NSTimer scheculedWith TimerInterval(4.0) target:(self)selector:@selector(httpRequest) userinfo:nil repeats:YES]
    }
    -(void)httpRequest{

    _weak ASIHTTPRequest *request1 = [ASIHTTPRequest requestWithURL:url1];
    [request1 setCompletionBlock:^{
        NSString *responseString1 = [request1 responseString];
    //dispatch_async(backgroundProcess1,^(void){
        [self plotOverlay1:responseString1];
     //});
    }];
    [request1 setFailedBlock:^{
        NSError *error=[request1 error];
        NSLog(@"Error: %@", error.localizedDescription);
    }]; 

    [request1 startAsynchronous];
    }

回答1:

If you just want the data to be updating continuously, consider calling -httpRequest again from within the completion block of the first request (and removing the timer). That way, you can be assured that the request will get performed again, but only after the first request finishes - and you can introduce a delay there, so you get something like "check again two seconds after the first check finishes."

This might look something like:

- (void)httpRequest {
    __weak ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:url1];
    [req setCompletionBlock:^{
        NSString *resp = [req responseString];
        [self plotOverlay1:resp];

        [self httpRequest];
        // or...
        [self performSelector:@selector(httpRequest) withObject:nil afterDelay:2.0];
    }];
    /* snip fail block */
    [req startAsynchronous];
}