iOS12下APP进入后台后再返回前台连接断开

Posted 淡然微笑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS12下APP进入后台后再返回前台连接断开相关的知识,希望对你有一定的参考价值。

 

在release环境下,APP在ios12的时候退到后台然后再返回到前台的时候网络请求返回错误,AFN返回错误码53,NSPOSIXErrorDomain Code=53: Software caused connection abort。但是在Debug环境下却没发现这个问题,其他系统版本下也没有问题,所有就怀疑是不是iOS12的原因。

最后在github上 AFNetworking的留言中发现了国外的开发者也遇到了这个问题,并且给苹果发了邮件,也收到了苹果的回复,https://github.com/AFNetworking/AFNetworking/issues/4279

 

虽然给的回复是问题出在苹果那边,但是也不知道苹果啥时候解决这个问题,所以遇到的问题还得解决,最后推测是退到后台的时候系统挂起了APP,既然有10分钟,那么就一定要争取到!所以申请后台任务:

1.在工程的AppDelegate文件中

@interface AppDelegate ()
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier taskId;
@property (nonatomic, strong) NSTimer *timer;
@end

2.在AppDelegate中的- (void)applicationDidEnterBackground:(UIApplication *)application 方法中

self.taskId =[application beginBackgroundTaskWithExpirationHandler:^(void) {
        //当申请的后台时间用完的时候调用这个block
        //此时我们需要结束后台任务,
        [self endTask];
    }];
// 模拟一个长时间的任务 Task
 self.timer =[NSTimer scheduledTimerWithTimeInterval:1.0f
                                                   target:self
                                                 selector:@selector(longTimeTask:)
                                                 userInfo:nil
                                                  repeats:YES];

3.结束后台任务后台任务结束的时候要释放定时器

#pragma mark - 停止timer
-(void)endTask
{

    if (_timer != nil||_timer.isValid) {
        [_timer invalidate];
        _timer = nil;
        
        //结束后台任务
        [[UIApplication sharedApplication] endBackgroundTask:taskId];
        taskId = UIBackgroundTaskInvalid;
        
        NSLog(@"停止timer");
    }
}

4.模拟的长时间后台任务

- (void) longTimeTask:(NSTimer *)timer{
    
    // 系统留给的我们的时间
    NSTimeInterval time =[[UIApplication sharedApplication] backgroundTimeRemaining]; 
    NSLog(@"系统留给的我们的时间 = %.02f Seconds", time);
  
}

这样App就不会一进入后台就会被挂起

 

 

以上是关于iOS12下APP进入后台后再返回前台连接断开的主要内容,如果未能解决你的问题,请参考以下文章

iOS App生命周期及AppDelegate方法

当应用程序从后台返回到前台时,MCSession 无法重新连接

ios 监听app从后台恢复到前台

iOS App 在后台运行 - 需要使用 Graph 删除 removeFilePresenter

进程测试

iOS 保证定时器进入后台依然运行