Swift 3: Checking if app is in background

Viewed 2663

I need to check if the app is moved to the background. Why?

Well because my app works with bluetooth and only one person can be connected to this device at a time. Therefore if they are not using it and the app is in the background, disconnect them and send them to the connect main page.

Now I have accomplished this. I have a selector in the main first class and a function to disconnect and send to first page. But what I didn't realise is that if the control panel is dragged up, the app is in the 'background'.

From looking around there doesn't seem to be a way to detect if the control panel is brought up. So does anyone have any ideas on how I can do this differently?

Realistically I just want it so if the app is moved to the background for any other reason than the control panel being brought up, disconnect from the device.

Selector:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)

Function:

@objc func appMovedToBackground() {
        if (ViewController.connectedPeripheral != nil) {
            print("App moved to background!")
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "connectView") as! ViewController
            self.navigationController?.pushViewController(nextViewController, animated: true)
            ViewController.centralManager.cancelPeripheralConnection(ViewController.connectedPeripheral!)
        }
        else {
            print("App moved to background but no device is connected so no further action taken")
        }
    }

This is not a duplicate of other questions. I know how to check if app is in background state. I just don't want to disconnect when the control panel is brought up...

3 Answers
Related