使用来自@apptality 的一些详细信息,我能够使用 Darwin Notifications 来实现这一点。 This answer 解释了如何让通知工作。我使用以下代码来执行此操作:
在 AppDelegate 的 didFinishLaunchingWithOptions 方法中放置以下代码:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
(void*)self, // observer (can be NULL)
lockStateChanged, // callback
CFSTR("com.apple.springboard.lockcomplete"), // event name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately);
然后使用这个方法来处理通知:
static void lockStateChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
NSLog(@"event received!");
if (observer != NULL) {
AppDelegate *this = (__bridge AppDelegate*)observer;
NSString* notifyName = (__bridge NSString*)name;
if ([notifyName isEqualToString:@"com.apple.springboard.lockcomplete"]) {
[this localNotificationSetup];
}
}
}
localNotificationSetup 是您注册发送通知的位置。请小心,因为这是一种基于 c 的方法,因此您的大部分 Objective-c 代码都需要更改。然后,您可以使用此方法来处理通知上的操作:
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
要真正完成任何有用的事情,如果您的应用进入睡眠状态,您可能需要在此方法中从 nsuserdefaults 加载数据。