Differentiate between screen lock and home button press on iOS7

前端 未结 3 1849
生来不讨喜
生来不讨喜 2020-12-03 11:24

I need to do something in applicationDidEnterBackground. But I need to differentiate which user action causes the \"enter background\": screen lock or home butt

3条回答
  •  -上瘾入骨i
    2020-12-03 12:18

    It doesn't work in Swift, you need to do some modification to make it work in Swift as follow

    1.create a objectiveC file named LockNotifierCallback.m as follow:

    static void displayStatusChanged(CFNotificationCenterRef center,
                                     void *observer,
                                     CFStringRef name,
                                     const void *object,
                                     CFDictionaryRef userInfo) {
        if ([(__bridge NSString *)name  isEqual: @"com.apple.springboard.lockcomplete"]) {
            NSLog(@"Screen Locked");
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kDisplayStatusLocked"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
    
    @implementation LockNotifierCallback
    
    + (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc {
    return displayStatusChanged;
    }
    
    @end
    

    create a head as well: #import

    @interface LockNotifierCallback : NSObject
    
    
    + (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;
    
    
    @end
    

    2.bridge this file to swift

    3.add function to APPdelegate.swift:

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, LockNotifierCallback.notifierProc(), "com.apple.springboard.lockcomplete", nil, CFNotificationSuspensionBehavior.DeliverImmediately)
    

    PS:UIApplicationState doesn't work perfectly in here

提交回复
热议问题