美文网首页
iOS杀死程序后数据上报

iOS杀死程序后数据上报

作者: 小王在努力 | 来源:发表于2020-10-26 09:55 被阅读0次

    1、前言

    杀死进程 ,网络请求调用如果是在子线程.这个时候RunLoop循环已经结束,此时网络请求进行到一半就会停止,所以不会回调回来。
    这是时候我们只需要在主线程做网络请求,难后sleep2秒。服务器就可以正常下发数据
    

    2、代码实现

    func applicationWillTerminate(_ application: UIApplication) {
    
            print("applicationWillTerminate")
    
            let path : URL = URL.init(string: "[https://api.zhuishushenqi.com/cats/lv2/statistics](https://api.zhuishushenqi.com/cats/lv2/statistics)")!
    
            let conifg : URLSessionConfiguration = URLSessionConfiguration.default;
    
            let session : URLSession = URLSession.init(configuration: conifg);
    
            var request = URLRequest.init(url: path)
    
            request.timeoutInterval = 10;
    
            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
    
            request.addValue("chrome", forHTTPHeaderField:"User-Agent")
    
            let task : URLSessionDataTask = session.dataTask(with: request) { (data, respond, error) in
    
                let json = JSON(data as Any)
    
                print(json)
    
            }
    
            task.resume();
    
            sleep(2)
    
            print("=================")
    
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
        }
    

    3、用户切后台在杀死程序这时候我们改怎么做
    程序进入后台后,如果内存不足被系统杀死或者手动杀死,都不会调用 applicationWillTerminate
    解决方法:可以在程序进入后台时,添加一后台运行通知函数,也就是程序进入后台一段时间内,程序还在运行,并可以响应一些消息。

        func applicationDidEnterBackground(_ application: UIApplication) {
    
            print("applicationDidEnterBackground")
    
            UIApplication.shared.beginBackgroundTask {
    
            }
    
        }
    
        func applicationWillTerminate(_ application: UIApplication) {
    
            print("applicationWillTerminate")
    
            let path : URL = URL.init(string: "[https://api.zhuishushenqi.com/cats/lv2/statistics](https://api.zhuishushenqi.com/cats/lv2/statistics)")!
    
            let conifg : URLSessionConfiguration = URLSessionConfiguration.default;
    
            let session : URLSession = URLSession.init(configuration: conifg);
    
            var request = URLRequest.init(url: path)
    
            request.timeoutInterval = 10;
    
            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
    
            request.addValue("chrome", forHTTPHeaderField:"User-Agent")
    
            let task : URLSessionDataTask = session.dataTask(with: request) { (data, respond, error) in
    
                let json = JSON(data as Any)
    
                print(json)
    
            }
    
            task.resume();
    
            sleep(2)
    
        }
    
    

    相关文章

      网友评论

          本文标题:iOS杀死程序后数据上报

          本文链接:https://www.haomeiwen.com/subject/wnfbmktx.html