如何在应用程序处于后台时调用操作方法或功能

时间:2018-06-06 08:57:27

标签: ios

我正在为设备中的动作检测创建应用程序。当app处于前台运动时,检测方法用于调用和工作。但是,当应用程序处于后台时,它无法正常工作。迅速

2 个答案:

答案 0 :(得分:0)

var backGroundTask : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

Add the observer when app will enter the back ground.
NotificationCenter.default.addObserver(self, selector: #selector(registerBackGroundTask), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(appDidBecameActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)

@objc func registerBackGroundTask () {
    backGroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundTask()
    })
    assert(backGroundTask != UIBackgroundTaskInvalid)
}

@objc func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(backGroundTask)
    backGroundTask = UIBackgroundTaskInvalid
}


@objc func appDidEnteredBackground() {
    let deadlineTime = DispatchTime.now() + .seconds(countTime)
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
        if (self.activateButton?.isSelected)! {
           self.startDetectingMotion()
        }

    }
}
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecameActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
 @objc func appDidBecameActive() {
     motionManager.stopDeviceMotionUpdates()
}

When u will start task in background then u have to stop after complete the task. 
This code will be valid only when your app is like background music play app, news app, any IOT device app. if it is not type this app apple will reject the app.

答案 1 :(得分:-1)

DispatchQueue.global(qos:.background).async {     func yourFunction(){}

}