【问题标题】:Runloop always cause XPC connection interrupted?Runloop总是导致XPC连接中断?
【发布时间】:2018-02-13 06:14:51
【问题描述】:

您好,我注意到如果我在应用进入后台时添加 runloop 会导致 XPC 连接中断

例如,我的应用程序连接到一个BLE设备,如果用户让应用程序进入后台一段时间,我将退出应用程序而不是释放连接

这是我的代码

func applicationDidEnterBackground(_ application: UIApplication) {
        isInBackground = true
        timer = Timer.scheduledTimer(timeInterval: 300 , target: self, selector: #selector(self.quitApp), userInfo: nil, repeats: false)
        RunLoop.current.add(timer, forMode: .commonModes)
        RunLoop.current.run()
    }

func quitApp() {
    if isInBackground == true {
        print("QUIT APP")
        exit(0)
    }
}

func applicationWillEnterForeground(_ application: UIApplication) {
        timer.invalidate()
        isInBackground = false
}

但每次我进入前台,我发现如果我删除了运行循环

func applicationDidEnterBackground

应用程序将运行

func applicationDidBecomeActive 
or 
func applicationWillEnterForeground

但是如果我添加 Runloop ,它会导致

XPC 连接中断

我不明白 Runloop 和应用生命周期有什么关系???

另外,如果我让应用程序进入后台足够的时间,应用程序将退出,然后再次打开应用程序一切都很好。

******更新******

这是我使用的最终代码,它运行良好,没有崩溃 但不确定是不是因为我修改了我的项目设置...... 这是很久以前的问题了

func applicationDidEnterBackground(_ application: UIApplication) {

    //Quit if Enter background 5 min
    isInBackground = true
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(quitApp), userInfo: nil, repeats: true)
    timer.fire()
    RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
    let app = UIApplication.shared
    var bgTask:UIBackgroundTaskIdentifier? = UIBackgroundTaskInvalid
    bgTask = app.beginBackgroundTask{ () -> Void in
        DispatchQueue.main.async{
            if bgTask != UIBackgroundTaskInvalid{
                bgTask = UIBackgroundTaskInvalid
            }
        }
    }
}

func applicationDidBecomeActive(_ application: UIApplication) {
    timer.invalidate()
    isInBackground = false
    backgroundCount = 0
}

@objc func quitApp() {
    if backgroundCount < 300 {
        backgroundCount += 1
    }else {
        if isInBackground == true {
            exit(0)
        }
    }
}

【问题讨论】:

  • 你是怎么解决的?我面临与 RunLoop 相同的问题 XPC。
  • 我更新了我的代码,不确定它是否对你有帮助,但我的应用程序现在没有崩溃

标签: ios swift appdelegate xpc runloop


【解决方案1】:

XPC 是使用运行循环实现的,因此篡改运行循环会中断您的 XPC 连接也就不足为奇了。

【讨论】:

  • 谢谢!也许我需要避免使用 runloop
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 2015-12-17
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多