0

我需要后台进程(用于调用网络服务)在应用启动状态时调用 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");
    }
}
4

2 回答 2

1

这就是我创建本地通知的方式,该通知安排在此代码运行当天的 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];
于 2013-06-04T12:44:37.387 回答
0

2例收到通知

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

l

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
            UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];  
            if (localNotif) {       
                // Show Alert Here
            }
    }
于 2013-06-04T13:06:07.150 回答