2

I found answer for iOS 5 on my question, but what about iOS10? Can there is an implementation on Swift3? for iOS 5:

// Pressing the home button
Will resign active.
Did enter background.
// Tapping app icon on Springboard
Will enter foreground.
Did become active.

// Pressing the lock button
Will resign active.
Did enter background.
// Unlocking the device
Will enter foreground.
Did become active.
Community
  • 1
  • 1
Vadim Nikolaev
  • 2,132
  • 17
  • 34

2 Answers2

1

Yes you can, when screen is locked the notification named com.apple.springboard.lockcomplete is called.

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                    nil, { (_, observer, name, _, _) in
                                            print("Locked") 
                                         },
                                    "com.apple.springboard.lockcomplete" as CFString!,
                                    nil, deliverImmediately)

For detecting background/foreground mode you need to listen notifications.

 NotificationCenter.default.addObserver(self, selector:#selector(handleForegroundMode), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
 NotificationCenter.default.addObserver(self, selector:#selector(handleBackgroundMode), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
1

Please don't observe "com.apple.springboard.lockcomplete" notification. Apple refined their app scanner tool recently, the notification is part of private API, if you still observe this notification, your app will get rejected during submission.

evanchin
  • 2,028
  • 1
  • 22
  • 25