本文首發(fā)在我的個(gè)人博客:http://blog.shenyuanluo.com/泰佳,喜歡的朋友歡迎訂閱墨技。
最近公司有個(gè)項(xiàng)目需要對(duì)鎖屏進(jìn)行監(jiān)控以便進(jìn)行一些操作警没,然后在更新新版本的時(shí)候刑然,審核竟然被拒絕了。原因竟然是調(diào)用了 Apple 不允許使用的 鎖屏API 愉粤,如下方法一砾医;后來改成方法二,終于審核通過了衣厘。
鎖屏監(jiān)聽
-
方法一:(審核會(huì)被拒)
-
導(dǎo)入頭文件和宏定義
// AppDelegate.m #import <notify.h> #define NotificationLock CFSTR("com.apple.springboard.lockcomplete") #define NotificationChange CFSTR("com.apple.springboard.lockstate") #define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen") #define LOCK_SCREEN_NOTIFY @"LockScreenNotify"
-
定義監(jiān)聽鎖屏函數(shù)
// AppDelegate.m static void screenLockStateChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) { NSString *lockstate = (__bridge NSString *)name; if ([lockstate isEqualToString:(__bridge NSString *)NotificationLock]) { // 發(fā)送鎖屏通知 [[NSNotificationCenter defaultCenter] postNotificationName:LOCK_SCREEN_NOTIFY object:nil]; NSLog(@"Lock screen."); } else { // 此處監(jiān)聽到屏幕解鎖事件(鎖屏也會(huì)掉用此處一次藻烤,所有鎖屏事件要在上面實(shí)現(xiàn)) NSLog(@"Lock state changed."); } }
-
添加監(jiān)聽函數(shù)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); }
-
注意:該方法已被 Apple 禁止使用,上傳的 App 審核會(huì)被拒絕头滔!
-
-
方法二:(Apple 推薦使用的方法)
-
實(shí)現(xiàn)
applicationProtectedDataWillBecomeUnavailable:
方法監(jiān)聽鎖屏// AppDelegate.m #define LOCK_SCREEN_NOTIFY @"LockScreenNotify" - (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:LOCK_SCREEN_NOTIFY object:nil]; NSLog(@"Lock screen."); }
-
實(shí)現(xiàn)
applicationProtectedDataDidBecomeAvailable:
方法監(jiān)聽解鎖// AppDelegate.m #define UN_LOCK_SCREEN_NOTIFY @"UnLockScreenNotify" - (void) applicationProtectedDataDidBecomeAvailable:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:UN_LOCK_SCREEN_NOTIFY object:nil]; NSLog(@"UnLock screen."); }
-
官網(wǎng) API 說明如下:
When the user locks the device, the system calls the app delegate’s
applicationProtectedDataWillBecomeUnavailable:
method. Data protection prevents unauthorized access to files while the device is locked. If your app references a protected file, you must remove that file reference and release any objects associated with the file when this method is called. When the user subsequently unlocks the device, you can reestablish your references to the data in the app delegate’sapplicationProtectedDataDidBecomeAvailable:
method.
-