Detecting when iOS goes to sleep

In an app recently we wanted to know when the device went to sleep, as opposed to just went into the background. The reason was that the app needed to behave differently when it was opened again and therefore we had to save state when this event occured. The problem was that by default, iOS does not tell you what the user did to put the app into the background. Home or sleep button, you simply don't know.

After some digging around I can across some code that did what I wanted. It works by listening for events at a deeper level than tose normally generated by the iOS SDK. Here's the code:

// Callback function for when the system lock is used.
static void iosLocked(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);

-(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptionsDict {

    // Register a callback for when the system finishes locking. 
    // This is used to ensure that the usr has to login immediately after they
    // Lock the phomne.
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    (__bridge const void *)(self), // observer
                                    iosLocked, // callback function - see signature.
                                    CFSTR("com.apple.springboard.lockcomplete"), // Phone locked event
                                    NULL, // object to be passed?
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
    }

    //call back
    static void iosLocked(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    // Do your magic here!
}

To the best of my knowledge this is ligit code and should not stop you submitting to the app store. Enjoy.


Comments powered by Disqus