繁体   English   中英

如何在iPhone中调用didReceiveLocalNotification:(UILocalNotification *)notification?

[英]How to call didReceiveLocalNotification:(UILocalNotification *)notification in iPhone?

我需要后台进程(用于调用Web服务)在应用启动状态后调用didReceiveLocalNotification:(UILocalNotification *)notification,该怎么做,请帮帮我。

提前致谢

我尝试了这个:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{
    if (app.applicationState == UIApplicationStateInactive )
    {
        NSLog(@"app not running");
    }
    else if(app.applicationState == UIApplicationStateActive )
    {
        NSLog(@"app running");
    }
}

这就是我创建本地通知的方式,该通知计划在此代码运行的当天17:00进行。 触发后,将调用-(void)application:didReceiveLocalNotification:方法。

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
[dateComponents setHour:17];
[dateComponents setMinute:00];
[dateComponents setSecond:00];

NSDate *notificationDate = [calendar dateFromComponents:dateComponents];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = notificationDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

localNotif.alertBody = @"blah blah blah";
localNotif.alertAction = @"Ok";

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

在2种情况下收到通知

  1. application:didFinishLaunchingWithOptions:方法中,如果该应用程序既不在运行又不在后台运行。
  2. application:didReceiveLocalNotification:方法中,如果应用程序正在运行或在后台运行。 当应用程序已经运行时,几乎没有用来显示警报。 因此,您仅在通知触发时应用程序处于后台时才显示警报。 要了解该应用程序是否正在从后台恢复,请使用applicationWillEnterForeground:方法。

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
            UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];  
            if (localNotif) {       
                // Show Alert Here
            }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM