Timer vs ASIHTTPRequest - find optimal solution

蓝咒 提交于 2019-12-23 04:28:26

问题


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];
}


来源:https://stackoverflow.com/questions/12573980/timer-vs-asihttprequest-find-optimal-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!