iOS “Local” Push Notification [closed]

2019-01-30 16:54发布

问题:

Hey,

I'm looking for a way to make "local" push notifications. I can't figure out how I should do this, so I'm looking for some help. What I need is:

  • a way to send a notification for a user who haven't opened the application within 24 hours. (Or that an int havent change)

I really hope that one of you got time to help me, thanks!

回答1:

This is pretty straight forward:

1) When the app is closed, schedule a local notification that will fire in 24 hours

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
    notification.alertBody = @"24 hours passed since last visit :(";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

2) if the app is opened (before the local notification fires), cancel the local notification

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}


回答2:

You can use the UILocalNotification for this purpose.

And implement your UIApplication applicationWillTerminate and applicationDidEnterBackground delegates like:

- (void)applicationWillTerminate:(UIApplication *)application
{
   [self scheduleNotification];
}

 - (void)applicationDidEnterBackground:(UIApplication *)application
{
   [self scheduleNotification];
}

 - (void)scheduleNotification
{
   UILocalNotification *locNot = [[UILocalNotification alloc] init];
   locNot.fireDate             = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24];
   [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
}

When you enter to your app you need to cancel this notification. So implement applicationDidBecomeActive like;

- (void)applicationDidBecomeActive:(UIApplication *)application
{
   [[UIApplication sharedApplication] cancelAllLocalNotifications];
}


回答3:

UILocalNotification will suit you requirements Apple doc