1

嗨,我注意到如果我在应用程序进入后台时添加 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
}

但是每次我进入前台时,我发现如果我删除了runloop

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)
        }
    }
}
4

1 回答 1

-1

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

于 2017-09-05T06:42:31.097 回答