About sending local notifications before IOS10

Reference link: https://www.cnblogs.com/XYQ-208910/p/11777352.html

IOS4-IOS9 uses UILocalNotification to send local notifications, and IOS10 uses UNNotification.

Difference:

UILocalNotification and UNNotification are classes used to send local notifications and remote notifications in iOS, and there are some differences and different characteristics between them.

Variations supported by iOS version

UILocalNotification was introduced in iOS 4 and remained until iOS 9, but was deprecated in iOS 10. UNNotification was introduced in iOS 10 and is a brand new notification framework.

Supported notification content types

UILocalNotification only supports notifications with basic content like simple text, sound, number of app icons, etc. And UNNotification supports more notification content types, including rich text, pictures, videos, etc., and can customize the style and behavior of the notification interface.

Notification trigger mechanism

UILocalNotification uses the fireDate attribute to set the notification trigger time, while UNNotification supports multiple trigger conditions, such as time, location, user behavior, etc., and supports custom triggers.

Management and updates of notifications

Once a UILocalNotification is notified, its content cannot be updated again. And UNNotification provides a set of notification management and update mechanism, which can dynamically modify the notification content or delete the notification as needed. (Notifications cannot be updated while the app is in the background or not running; they can only be updated when the app is running.)

Customization of notifications

UNNotification has more flexible notification customization capabilities. You can use Notification Content Extension and Notification Service Extension to customize the display interface and content of notifications. At the same time, you can embed audio and video files in notifications to achieve a richer interactive experience.

To sum up, both UILocalNotification and UNNotification are classes for sending local notifications and remote notifications, and they have different characteristics and usage scenarios. If you need to send basic text notifications, you can consider using UILocalNotification; if you need to send and manage more and richer notification content, and support custom notification interface and interaction effects, you should use UNNotification.

1. Request permission

 // if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
    // //Start authorization
    // [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil]];
    // }else{
    // [self sendLocalNotify];
    // }

2. Create and register a notification class with two buttons

//AppDelegate.m
// create an editable notification action
    UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
    action1.identifier = @"CustomAction1";
    action1.title = @"Custom Action Title1";
    action1.activationMode = UIUserNotificationActivationModeForeground;
    action1.destructive = NO;
    action1.authenticationRequired = NO;
    // create an editable notification action
    UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];
    action2.identifier = @"CustomAction2";
    action2.title = @"Custom Action Title2";
    action2.activationMode = UIUserNotificationActivationModeForeground;
    action2.destructive = NO;
    action2.authenticationRequired = NO;
    
    // create an editable notification action class
    UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
    category.identifier = @"CustomActionCategory";
    [category setActions:@[action1,action2] forContext:UIUserNotificationActionContextDefault];
    
    // register notification action class
    NSSet *categories = [NSSet setWithObject:category];
    UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    

3. Registration notification

//Support versions below IOS10

- (void)sendLocalNotify {
    NSLog(@"Send local notification, code before IOS10");

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertTitle = @"Local push"; /// Notification title
    notification.alertBody = @"HELLO, welcome brother"; /// notification body
    notification.applicationIconBadgeNumber = 1; /// Application icon message number
    notification.hasAction = YES; /// Turn on the left slide button on the standby interface
    notification.alertAction = @"Open the app"; /// Sliding button reminder on the standby interface
    // Store custom information in the notification
    notification.userInfo = @{@"name":@"xyq"}; /// passed user data
    notification.soundName = UILocalNotificationDefaultSoundName; /// The sound played when the notification is received, the default message sound
    notification.category = @"CustomActionCategory";
    // Set the time interval for sending notifications repeatedly
    notification.repeatInterval = NSCalendarUnitMinute;
    
    // fire local notification after 10 seconds
    notification.fireDate = [NSDate date];
    notification.timeZone = [NSTimeZone defaultTimeZone];
    
    // Register for local notifications
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

4. Response notification trigger event

// Respond to the notification operation when the system runs the application
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)(void))completionHandler {
    NSDictionary *userInfo = notification. userInfo;
    if ([identifier isEqualToString:@"CustomAction1"]) {
        // Click the custom action button to execute related logic
        NSLog(@"Click the first button");
    }else{
        NSLog(@"Click the second button");
    }
    NSLog(@"Notification received with userInfo: %@", userInfo);
    // Processing after the operation is completed
    if (completionHandler) {
        completionHandler();
    }
}

5. Callback response event

/// When the user clicks to allow or not to allow, the following proxy method will be executed, in which we implement the processing logic
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    //If the notification type is not the non-display type, call the notification
    if (notificationSettings. types != UIUserNotificationTypeNone) {
        [self addLocalNotification];
    }
}

/// Receive local notifications when our application is in the foreground or enters the foreground from the background
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    // Make sure the app was launched from a notification
    if (application. applicationState == UIApplicationStateInactive) {
        // Add logic to handle local notifications here
        
        if (notification) {
            // mark the notification as handled
            notification. applicationIconBadgeNumber = 0;
            NSDictionary *userInfo = notification. userInfo;
            NSString *body = notification. alertBody;
            // NSLog(@"2----notification------- %@",notification);
            NSLog(@"2----userInfo------- %@",userInfo);
            NSLog(@"2----alertBody------- %@",body);
        }
    }
}

/// When our application enters the foreground, we need to clear the number of the application icon
-(void)applicationWillEnterForeground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

Achieve the effect:

1. Exit the app to send regularly

2. Add messaging

3. Add buttons and trigger events

4. Ability to display the number of notifications in the upper right corner of the icon

5. The app icon can be changed automatically to switch

PS:

1. There are restrictions on the custom UI design of notifications, which are title and main content, and attachments cannot be added. You can customize the prompt sound.

2. When the app is in the foreground, it will not send notifications by default. If you want to send notifications in the foreground, you need to deal with it separately.

3. After opening the app, the previous notification will disappear.