こんにちは、アプリがバックグラウンドに入るときにランループを追加すると、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
}
しかし、 foreground に入るたびに、実行ループを削除するとわかりました
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)
}
}
}