计时器与ASIHTTPRequest-找到最佳解决方案 [英] Timer vs ASIHTTPRequest - find optimal solution

查看:55
本文介绍了计时器与ASIHTTPRequest-找到最佳解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下所示,单击后我有一个按钮,它每4秒激活一次计时器和计时器调用方法.但是,有时4秒不足以使服务器返回数据.但是,如果服务器在1秒钟内返回数据,则增加计时器值也不是一个好的解决方案,并且不利于用户等待更长的时间.在这种情况下,我不知道什么是最佳/最佳解决方案.

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

推荐答案

如果只想连续更新数据,请考虑从第一个请求的完成块中再次调用-httpRequest(并删除计时器).这样,您可以放心,该请求将再次执行,但仅在第一个请求完成后 -并且您可以在此处引入延迟,因此您会得到类似重新检查请求后两秒钟"的信息.第一次检查完成."

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

这可能看起来像:

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

这篇关于计时器与ASIHTTPRequest-找到最佳解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆