UIUserNotification
is deprecated since iOS10, and we use UNUserNotification
instead. We need to import UserNotifications
- Set up the delegate: usually did in
didFinishLaunchingWithOptions
in AppDelegate
UNUserNotificationCenter.currentNotificationCenter.delegate = self;
- Register the remote notification: usually did in
didFinishLaunchingWithOptions
in AppDelegate
UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
[UNUserNotificationCenter.currentNotificationCenter requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if(!error){
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}
}];
- UNUserNotificationCenterDelegate Methods
// called when a notification is delivered to a foreground app.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
}
// called when the user clicked the notification
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = response.notification.request.content.userInfo;
// customize code here
completionHandler(UNNotificationPresentationOptionAlert);
}
// called when a remote notification is received
// content-available should be set to true for the delegate to be called
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// customize code here
completionHandler(UIBackgroundFetchResultNoData);
}
- How to schedule a notification
UNMutableNotificationContent *content = UNMutableNotificationContent.new;
content.title = @"this is a title";
content.body = @"body message";
content.userInfo = @{@"userID": @(100)};
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1
repeats:NO];
NSString *identifier = @"test";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content
trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request
withCompletionHandler:^(NSError * _Nullable error)
{
if (error) {
// something went wrong!!
}
}];