iOS 网络请求中,切换后台或者来电话了,导致网络请求错误

资料:https://stackoverflow.com/questions/65000773/network-connection-lost-while-switching-from-phone-call-to-app

问题总结

在网络较慢的时候 ,App 切到后台 或者 锁屏 网络请求报错 -1005

找的的资料:

StackoverFlow问题:https://stackoverflow.com/questions/65000773/network-connection-lost-while-switching-from-phone-call-to-app

alamofireissues:https://github.com/Alamofire/Alamofire/issues/872

Apple文档:https://developer.apple.com/forums/thread/85066

后台任务中文资料:https://juejin.cn/post/7213915505487757349?searchId=202412161344025F38682C8B3C6F2E9371

一旦切换到另一个应用程序,该应用程序就会退出活动状态并暂停

目前解决方案是

在applicationWillResignActive 即将进入失去活动状态的时候

UIApplication.shared.beginBackgroundTask 开启一个后台刷新任务

加了这个代码后进行了20多次测试没出现过了。

下面是解决代码

在APPDelegate 中

var backgroundUpdateTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)
func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
}
func applicationWillResignActive(_ application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundUpdateTask()
    })
}
func applicationDidBecomeActive(_ application: UIApplication) {
    self.endBackgroundUpdateTask()

}

在SceneDelegate 中

 var backgroundUpdateTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)
    
        func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
    }
    
        func sceneWillResignActive(_ scene: UIScene) {
        print("sceneWillResignActive 应用中的场景即将失去活跃状态")
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
             self.endBackgroundUpdateTask()
         })
    }
    
       func sceneDidBecomeActive(_ scene: UIScene) {
        // 应用进入前台时的处理
        print("sceneDidBecomeActive 当应用即将进入前台运行时调用")
        self.endBackgroundUpdateTask()
        }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容