-2

Trying to figure out, with my app, how to make the app know when the phone is locked or when the app is minimized and using another app.

This is what i have so far:

//warning notification
func warningNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Go back to app immediately to prevent"
    //        content.body = publictime
    //        print("Notification timer\(content.body)")
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
                                                    repeats: false)

    let requestIdentifier = "demoNotification"
    let request = UNNotificationRequest(identifier: requestIdentifier,
                                        content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request,
                                           withCompletionHandler: { (error) in
                                            // Handle error
    })

}
swstrau118
  • 181
  • 4
  • 7
  • 15
  • 1
    Check your app's background Stage on appDelegate – Eddwin Paz Mar 23 '19 at 02:15
  • Possible duplicate.. https://stackoverflow.com/questions/31429800/how-to-check-if-the-ios-device-is-locked-unlocked-using-swift?noredirect=1&lq=1 – Mocha Mar 23 '19 at 05:51

2 Answers2

0

Take a look at the default functions inside your AppDelegate. In your situation you might be interested in applicationWillResignActive, applicationDidEnterBackground, or applicationWillTerminate.

Hamer
  • 1,354
  • 1
  • 21
  • 34
0

There are a few ways to achieve these things; however, currently to my knowledge, it is not possible to know for sure if a user is now using another app. You can tell if a user has put your app into the background. Once an app is in the background, they are either going to the home screen or opening another app.

You can achieve this by looking at the function applicationDidEnterBackground(_:)

optional func applicationDidEnterBackground(_ application: UIApplication)

Apple Docs for DidEnterBackground

You can access this in the App Delegate or register for notification if you are putting your code in another class or view controller.

Screen lock on stackoverflow

More screen lock on stackoverflow

As for detecting if the phone has been locked, there are a few posts already on StackOverflow about this. However, looking at these it may not be possible with Native code, and even the private API's they suggest do not seem to work very well.

You should be able to achieve what you need using the delegate methods Apple provides. Take a more in-depth look at the docs. If you let me know why you need access to these things I always happy to give more advice as it is not 100% clear from your code.

More Apple Docs

AlexanderKaran
  • 515
  • 6
  • 18