在达尔文通知中心回拨电话UIAlert

时间:2016-05-17 16:45:14

标签: ios objective-c uiviewcontroller ios9

我在ViewDidLoad上创建了一个Darwin Notification,我想在调用回调时调用UIAlert。在这种情况下,我想在屏幕解锁时调用警报,为此我将创建一个变量,当第二次调用此回调时将设置为TRUE / YES(考虑到第一次将当用户锁定屏幕时,第二次当用户解锁屏幕时)。当此变量为TRUE / YES时,将调用警报。

我该怎么做?

我的代码:

- (void)viewDidLoad {
[super viewDidLoad]; 
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), 
                                NULL, 
                                hasBlankedScreen, 
                                CFSTR("com.apple.springboard.hasBlankedScreen"), 
                                NULL, 
                                CFNotificationSuspensionBehaviorDeliverImmediately);
}

static void hasBlankedScreen(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    /*
    if(isUnlocked){
        [self myAlert];
    } else{
        isUnlocked = true;
    } 
    */
}

- (void) myAlert{
    UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:@"HEY"
                                  message:@"Screen is unlocked"
                                  preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self pop];
                                                          }];

    [alert addAction:defaultAction];

    [self presentViewController:alert animated:YES completion:nil];
}

1 个答案:

答案 0 :(得分:0)

这很简单:

1)将(const void*)self作为观察者传递到CFNotificationCenterAddObserver而不是NULL;

2)在(__bridge ViewController*)observer而不是hasBlankedScreen中使用self

完整代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
                                    (const void*)self,
                                    hasBlankedScreen,
                                    CFSTR("com.apple.springboard.hasBlankedScreen"),
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}

static void hasBlankedScreen(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
     if (self.locked) {
         [(__bridge ViewController*)observer myAlert];
         self.locked = NO;
     } else {
         self.locked = YES;
     }
}