gpt4 book ai didi

ios - 发送多个 NSURLSession

转载 作者:行者123 更新时间:2023-11-29 02:12:42 26 4
gpt4 key购买 nike

我有一个看起来像这样的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com