Ruturaj Desai
Ruturaj Desai

Reputation: 116

iOS Silent local push notifications objective c?

I am searching for way to implement silent local push notifications. I want to send silent notification to user when that user is out of range.

Upvotes: 2

Views: 3791

Answers (1)

Ruturaj Desai
Ruturaj Desai

Reputation: 116

Solved. While creating local notification don't set following values.

notification.alertBody = message;
notification.alertAction = @"Show";
notification.category = @"ACTION"; 
notification.soundName = UILocalNotificationDefaultSoundName;

Just crate local notification like this:

UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
NSTimeZone* timezone = [NSTimeZone defaultTimeZone];
notification.timeZone = timezone;
notification.applicationIconBadgeNumber = 4;
[[UIApplication sharedApplication]scheduleLocalNotification:notification];

This will send local notification and will only display IconBadgeNumber as 4. No notification will be shown in notification center when app is in background.

Updated for iOS10 (UNUserNotificationCenter)

In AppDelegate

@import UserNotifications;

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge;

[center requestAuthorizationWithOptions:options
                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
                          if (!granted) {
                              NSLog(@"Something went wrong");
                          }
                      }];

In ViewController

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
//content.title = @"Don't forget";
//content.body = @"Buy some milk";
//content.sound = [UNNotificationSound defaultSound];
content.badge = [NSNumber numberWithInt:4];

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:15 repeats:NO];


NSString *identifier = @"UniqueId";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                      content:content trigger:trigger];

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Something went wrong: %@",error);
    }
}];

This will send a silent notification after 15 sec with badge count as 4.

Upvotes: 6

Related Questions