UILocalNotification的警报行动代码

Cha*_*ndu 9 iphone xcode objective-c ios

UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [self.datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];

notif.alertBody = @"Did you forget something?";
notif.alertAction = @"Show me";
Run Code Online (Sandbox Code Playgroud)

如果用户点击"showme"应用程序应该打开,他应该收到警报.我应该在哪里写这个代码?如果可能的话,有人请给我一些代码

Emp*_*ack 24

根据应用程序触发通知时的状态,您将在两个位置获得有关UILocalNotification的通知.

1.在应用程序中:didFinishLaunchingWithOptions:方法,如果应用程序既不运行也不在后台运行.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];  
    if (localNotif) {       
        // Show Alert Here
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

2.在应用程序中:didReceiveLocalNotification:方法,如果应用程序正在运行或在后台运行.当应用程序已经运行时,显示警报几乎没用.因此,只有在通知触发时应用程序处于后台时才必须显示警报.要知道应用程序是否从后台恢复,请使用applicationWillEnterForeground:方法.

- (void)applicationWillEnterForeground:(UIApplication *)application {

    isAppResumingFromBackground = YES;
}
Run Code Online (Sandbox Code Playgroud)

使用此功能,只有当应用程序从后台恢复时,才能在didReceiveLocalNotification:方法中显示警报.

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    if (isAppResumingFromBackground) {

        // Show Alert Here
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要在通知被触发时始终显示警报视图,可以简单地省略if条件,而不管应用程序的状态如何.