2016-05-17 3 views
2

私はViewDidLoadでダーウィン通知を作成しました。コールバックが呼び出されたときにUIAlertを呼びたいと思います。この場合、画面がロックされていないときにアラートを呼び出すと、このコールバックが2回目に呼び出されたときにTRUE/YESに設定される変数を作成します(最初のユーザーが画面をロックしたときと、ユーザーが画面をロック解除したときの2回目)。この変数がTRUE/YESの場合、アラートが呼び出されます。ダーウィン通知センターコールバックで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)CFNotificationCenterAddObserver代わりのNULLにオブザーバーとして(const void*)selfを渡します。

2)selfの代わりにhasBlankedScreen(__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; 
    } 
} 
関連する問題