【问题标题】:How to re-send/re-queue failed requests with ASIHTTP?如何使用 ASIHTTP 重新发送/重新排队失败的请求?
【发布时间】:2011-06-01 08:11:52
【问题描述】:

我正在尝试实现一个排队系统,以便在 iphone 应用程序中将内容发送到网络服务。 该代码有效,但如果由于网络错误等原因导致连接失败,请求将被丢弃。

我希望我的应用程序重新排队该请求,而不是仅仅删除它,但我想不出办法吗?我试过这样做:

(void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(@"Error: %@",error);

//Re-queue the request
[[self queue] addOperation:request];
}

但这只会给我一个错误提示:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***      -[ASINetworkQueue addOperation:]: operation is finished and cannot be enqueued'

我在这里做错了什么?

【问题讨论】:

标签: ios asihttprequest


【解决方案1】:

我也有这样的设置。我有一个后台线程,每 30 秒左右轮询一次我的服务器。如果连接失败,它会将“isOnline”设置为 false。我所有的请求都会检查是否有网络连接,如果有任何请求未能到达服务器,则认为网络连接已丢失。

// Create operation...
[networkQueue addOperation:theOperation];
if( isOnline == YES )
    [networkQueue go];
else:
    [displayAlert message:@"The operation is waiting for a connection"];

当我确定连接恢复时,我的后台线程会这样做:

-(void)setIsOnline:(BOOL)val {
    if( isOnline == NO && val == YES ) {
        [networkQueue go];
    }

    isOnline = val;
 }

最困难的部分是 requestDidFail 方法,您必须在该方法中重新创建队列,否则您将丢失最先发现坏网络连接的操作。这是我的方法的样子:

-(void)requestDidFail:(ASIHTTPRequest*)aRequest {
       // If we find that the network is down, recreate the queue and
       // add our operation to it in suspended mode.
       if( [aRequest.error code] == ASIConnectionFailureErrorType ) {
           isOnline = NO;
           [networkQueue setSuspended:YES];
           [networkQueue cancelAllOperations];
           self.networkQueue = nil;

           ASINetworkQueue *aQueue = [[ASINetworkQueue alloc] init];
           self.networkQueue = aQueue;
           [networkQueue setDelegate:self];
           [aQueue release];
       }

       // Don't add any cancelled requests back into the queue
       if( [aRequest.error code] != ASIRequestCancelledErrorType ) {
           [networkQueue addOperation:[aRequest copy]];
       }

    }

现在您将在设备离线时开始排队请求。一旦该后台线程看到网络连接,队列就会开始处理,一切都会通过。

当然需要更多的错误检查,但希望这是一个很好的起点。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。您可以简单地复制请求:

    [[self queue] addOperation:[request copy]];
    

    不确定内存管理对我在这里所做的事情有何影响...

    【讨论】:

      【解决方案3】:

      只是猜测:也许操作不能多次排队,必须重新创建?

      【讨论】:

        猜你喜欢
        • 2020-11-09
        • 2012-02-11
        • 2015-12-08
        • 1970-01-01
        • 2015-08-31
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多