连接返回时重新发送ASIHTTPRequest

时间:2012-06-10 14:54:59

标签: ios queue asihttprequest nsoperation nsoperationqueue

我正在使用ASIHTTPRequest与我的网站进行互动。我基本上是将ASIHttpRequests添加到队列中。如果有互联网连接,一切正常。但是,我想如果请求失败(即没有互联网连接),操作将被删除

有没有办法在互联网连接时排队并执行请求?如果没有互联网连接,请求应排队并在连接返回时自动发送。如果这是不可能的,那么完成我在这里尝试的最佳方法是什么?

谢谢!

这就是我现在正在设置队列的方式:

NSURL *url = [NSURL URLWithString:@"http://www.tst.com.au/test.php?op=updateField"];

        ASIFormDataRequest *startHourRequest = [ASIFormDataRequest requestWithURL:url];

        NSDateFormatter *apiformatter = [[ [NSDateFormatter alloc] init] autorelease];
        [apiformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *webdate = [apiformatter stringFromDate:date];
        [startHourRequest setDelegate:appDelegate];
        [startHourRequest setPostValue:webdate forKey:@"fieldvalue"];
        [startHourRequest setPostValue:[appDelegate shiftuid] forKey:@"uid"];
        [startHourRequest setPostValue:editAttribute forKey:@"fieldname"];
        [startHourRequest setDidFinishSelector:@selector(requestDone:)];
        [startHourRequest setDidFailSelector:@selector(requestWentWrong:)];
        [[appDelegate queue] addOperation:startHourRequest];

1 个答案:

答案 0 :(得分:1)

是的,您可以使用Reachability类轻松地完成此操作:

首先,您将在发送初始请求之前检查互联网可达性:

Reachability *reachability = [Reachability reachabilityForInternetConnection];    
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
    //Do your request
}
else {
    //save your url to an array for use when the internet returns
}

并在视图控制器内或您发送请求的任何地方执行此操作以收听互联网更改

- (void)viewDidLoad

    [[NSNotificationCenter defaultCenter]
     addObserver:self 
     selector:@selector(networkStatusChanged:) 
     name:kReachabilityChangedNotification 
     object:nil];

    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];
}

- (void)networkStatusChanged:(NSNotification *)notice {
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    if (internetStatus != NotReachable && [yourUrlsToSend count] > 0) {
        //send off your requests now that you have internet

    }
}

这一切都取决于包含苹果的需求文件,可在此处找到:enter link description here。希望有所帮助