ios - 发送多个 NSURLSession

标签 ios nsurlconnection nsurlrequest nsurlsession

我有一个看起来像这样的 NSURLSession,我想做的是,如果没有返回数据,那么我希望它一次又一次地尝试,最多可以说 8 秒或尝试 3 次,然后如果仍然没有任何内容,我将让它不返回任何数据。这是我现在拥有的,

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlIn] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
    //use my data
    // if no data I want to try again?


}] resume];

所以我希望它尝试 3 次或直到 8 秒过去。我该怎么做,

提前感谢您的帮助。

最佳答案

好吧,我快完成了,我还有一点要用定时器来解决。这是我的。

我有属性

NSInteger attemptInt;
NSInteger _counter;
NSDate *date = [NSDate date];

然后这两个方法用于我的计时器

- (void)startCountdown
{
    _counter = 8;

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                      target:self
                                                    selector:@selector(countdownTimer:)
                                                    userInfo:nil
                                                     repeats:YES];
}

- (void)countdownTimer:(NSTimer *)timer
{
    _counter--;
    if (_counter <= 0) {
        [timer invalidate];
        NSLog(@"8 sec passed");
    }
}

然后这是我获取数据的地方。

- (void)getMenuItems:(NSString*)urlIn{
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:urlIn] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //One problem I am facing is I have to call timer for main thread
   if ([date timeIntervalSinceNow] <= 8 && [response expectedContentLength] == 0) {
        attemptInt++;
        [self getMenuItems:url];
    }
    if (attemptInt >= 3) {
        NSLog(@"NO DATA");
    }
    else if ([response expectedContentLength] == 0) {
        NSLog(@"TRY AGAIN");
        attemptInt++;
        [self getMenuItems:url];
    }
    else {
        //GOT MY DATA :)
        self.mealdata=[[MealData alloc]init:data];
    }

所以我已经完成了尝试,我是否设置了计时器我只需要一些帮助来完成检查是否先过了 8 秒?

关于ios - 发送多个 NSURLSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110675/

相关文章:

objective-c - 使用 AFNetworking 从中获取 JSON null

objective-c - 从 NSURLRequest 中移除一个 cookie

ios - 从应用程序 iOS9 打开设置

ios - 使用 NSURLConnection 的异步下载被证明是不可靠的

ios - 检查负值 iOS

ios - 使用 NSURLConnection 取消文件上传

ios - Monotouch 中的 objective-C mutableCopy 是如何实现的?

iphone - iOS 中的 NSData 和通过 POST 上传图片

ios - 从 safari 移动设备中的控制台打开链接

ios - 将捕获的图像存储到 UIImage 数组中 (AVFoundation)