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

时间:2013-06-04 12:31:01

标签: iphone ios background notifications uilocalnotification

我需要后台进程(用于调用web服务)在应用启动状态时调用didReceiveLocalNotification:(UILocalNotification *)通知,如何做到这一点,请帮帮我。

先谢谢

我试过了:

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

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

2例收到通知

  1. application:didFinishLaunchingWithOptions:方法中,如果应用是 既不跑也不在后台。
  2. 如果应用是application:didReceiveLocalNotification:方法 无论是跑步还是背景。它显示出几乎没用 应用程序已在运行时发出警报。所以你必须显示警报 仅当应用程序在通知时处于后台时 被解雇。要知道应用程序是否从后台恢复,请使用 applicationWillEnterForeground:方法。
  3. 1

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