2016-05-17 22 views
2

我在ViewDidLoad上創建了一個Darwin通知,我想在調用回調時調用UIAlert。在這種情況下,我想在屏幕解鎖時調用警報,這樣做時我將創建一個變量,當第二次調用此回調時將設置爲TRUE/YES(考慮到第一次會當用戶鎖定屏幕時,以及第二次用戶解鎖屏幕時)。當這個變量爲TRUE/YES時,警報將被調用。在Darwin通知中心回調中調用UIAlert

我該怎麼做?

我的代碼:

- (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]; 
} 

回答

0

這很簡單:

1)通(const void*)self觀察員進入CFNotificationCenterAddObserver代替NULL;

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

完整代碼:

- (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; 
    } 
}