How to fire a local notification in backround mode?

968 views Asked by At

After fetching new data in background, if any, I want to fire a local notification. I did this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    if ([application respondsToSelector:@selector(registerUserNotifitacionSetting:)]) {

        [application registerUserNotifitacionSetting:[UIUserNotificationSettings settingForTypes: UIUserNotificationTypeAlert|UIUserNotificationTypeBadge categories:nil]];
    }
    return YES;
}

- (void) application:(UIApplication *) application performFetchWithCompletionHandler: (void(^) (UIBackgroundFetchResult)) completionHandler {

    [self SendNotification];

    completionHandler(UIBackgroundFetchResultNewData);

}

-(void) SendNotification {    
    UILocalNotification *notification = [[UILocalNotification alloc]init];

    [notification setAlertBody:@"My text"];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:30]];
    [notification setTimeZone:[NSTimeZone defaultTimeZone]];
    notification.category = @"my category";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

In settings project I set Background Fetch and Remote Notification. When debugging logs in -(void) application:(UIApplication *) application performFetchWithCompletionHandler: (void(^) (UIBackgroundFetchResult)) completionHandler not displayed.

Please, tell me what am I doing wrong?

1

There are 1 answers

6
Sabhay Sardana On

In swift if you able to convert it then , this would be perfect iOS 8.3 (swift 1.2)

func applicationDidEnterBackground(application: UIApplication) {

let notification: UILocalNotification = UILocalNotification()
    notification.timeZone = NSTimeZone.defaultTimeZone()

    _ = NSDate()
    notification.fireDate = NSDate(timeIntervalSinceNow: (Time in seconds))
    notification.alertBody = "Alert Body"
    notification.alertAction = nil
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}