Can UILocalNotification be used to wake up a task

2019-02-14 11:13发布

问题:

I would like to know, if it is possible to somehow "wake up" a task that is in the background, to quickly check something on the network.. I think that this could be done with UILocalNotification, however, no matter what I tried, I could not get the didReceiveLocalNotification to do ANYTHING when the app is in the background.. After starting up, I immediately close the app by pressing the Home button (there is a 10 second delay for local notification to fire). This code works PERFECTLY when the app is in the foreground, and just kind of sitting there...

In app delegate header file:

 UILocalNotification *localNotif;

For testing, I set up local notification to fire quickly in the appDelegate startup.

localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];  // the date you want the notification to fire.
localNotif.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

NSLog(@"setup the timer for 10 seconds");





- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIApplicationState state = [application applicationState];
NSLog(@"getting kicked");
if (state == UIApplicationStateInactive) {

    // Application was in the background when notification was delivered.

    NSLog(@"INACTIVE..");
} else {
    NSLog(@"ACTIVE..");

}

}

回答1:

The user has a couple of choices: #1) Do they want to see a notification for your app. #2) If notifications are enabled for your app, do they want to click on your notification to launch your app. If they do accept notifications and open your notification while your app is in the background, application:didReceiveLocalNotification is called. To be clear, the user has to accept the notification (such as sliding the slider underneath the notification)... otherwise NOTHING is called.

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"%@", notification);
}

If your app has been terminated application:didFinishLaunchingWithOptions: is called -

- (BOOL)application:(UIApplication *) 
application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions {
    UILocalNotification *theNotification = 
      [launchOptions 
        objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    NSLog(@"%@", theNotification);

    return YES;
}