zoukankan      html  css  js  c++  java
  • 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就不会一进入后台就会被挂起

     

     

  • 相关阅读:
    VS Code C++ 代码格式化方法(clang-format)
    linux函数深入探索——open函数打开文件是否将文件内容加载到内存空间
    总结一下数据库的 一对多、多对一、一对一、多对多 关系
    netstat -st输出解析(二)
    Connection reset by peer的常见原因及解决办法
    Linux errno详解
    Linux之清理linux内存cache
    十大经典排序算法(动图演示)
    android studio导出apk
    多线程还是多进程的选择及区别
  • 原文地址:https://www.cnblogs.com/StevenHuSir/p/10108908.html
Copyright © 2011-2022 走看看