iOS 10.0以前以及以后本地通知注冊實現方法


以下是iOS8~iOS10注冊本地通知方式

  • iOS8-10注冊本地通知方式一樣
  • 以下我在程序啟動注冊本地通知,iOS8模擬器上
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 判斷系統版本號是否小於10.0
    NSString *version = [UIDevice currentDevice].systemVersion;
    if (version.doubleValue < 10.0) {
        // 參數5是觸發時間單位秒
        [self registerLocalNotification:5];
    }else{
//        [self regisNoti];
    }
    
    return YES;
}

// 注冊通知具體方法
- (void)registerLocalNotification:(NSInteger)alertTime {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 設置觸發通知的時間
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 時區
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 設置重復的間隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知內容
    notification.alertBody =  @"該起床了...";
    notification.applicationIconBadgeNumber = 1;
    // 通知被觸發時播放的聲音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知參數
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"開始學習iOS開發了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后,需要添加這個注冊,才能得到授權
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重復提示的單位,可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重復提示的單位,可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    // 執行通知注冊
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

  • - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSLog(@"noti:%@",notification) 此方法是在程序在前台接收到本地通知,或者在后台接收到通知並點擊通知橫幅會調用

#pragma mark - 本地通知回調
// 本地通知回調函數,當應用程序在前台接收到通知,或者后台點擊通知調用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"noti:%@",notification);
    
    // 這里真實需要處理交互的地方
    // 獲取通知所帶的數據
    NSString *notMess = [notification.userInfo objectForKey:@"key"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)"
                                                    message:notMess
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    
    // 更新顯示的badge個數
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge--;
    badge = badge >= 0 ? badge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
    
    // 在不需要再推送時,可以取消某一個推送(或者可以取消全部本地通知)
    [self cancelLocalNotificationWithKey:@"key"];
}



// 判斷程序是在前台還是后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //進入后台
    NSLog(@"后台");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // app啟動或者app從后台進入前台都會調用這個方法
    NSLog(@"前台");
    // 更新顯示的badge個數,每次進入我都設置為0
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}



#pragma mark - 取消某個(或者全部)本地推送通知
- (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 獲取所有本地通知數組
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根據設置通知參數時指定的key來獲取通知參數
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知,則取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                // 取消所有本地通知
//                [[UIApplication sharedApplication] cancelAllLocalNotifications];
                break;
            }
        }
    }
}


以下是iOS10以后注冊本地通知

  • 注冊通知方法,另外需要設置代理 UNUserNotificationCenterDelegate以及導入頭文件#import <UserNotifications/UserNotifications.h>

#pragma mark - iOS 10以上設置通知
-(void)regisNoti{
    // 使用 UNUserNotificationCenter 來管理通知
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //監聽回調事件
        center.delegate = self;
        //iOS 10 使用以下方法注冊,才能得到授權,注冊通知以后,會自動注冊 deviceToken,如果獲取不到 deviceToken,Xcode8下要注意開啟 Capability->Push Notification。
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                                  completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                      // Enable or disable features based on authorization.
                                  }];
        //獲取當前的通知設置,UNNotificationSettings 是只讀對象,不能直接修改,只能通過以下方法獲取
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        }];
        [self pushLocalNotifactionWithFireTime:5];
    }
}

// 發送通知具體方法
-(void)pushLocalNotifactionWithFireTime:(NSInteger)alerTime{
    // 使用 UNUserNotificationCenter 來管理通知
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        //需創建一個包含待通知內容的 UNMutableNotificationContent 對象,注意不是 UNNotificationContent ,此對象為不可變對象。
        UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
                                                             arguments:nil];
        content.sound = [UNNotificationSound defaultSound];
        content.userInfo = @{
                             @"a":@"v",
                             @"c":@"d",
                             };
        // 在 alertTime 后推送本地推送
        UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:alerTime repeats:NO];
        
        UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                              content:content trigger:trigger];
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            
        }];
        
    }
}

  • 實現iOS10本地通知代理方法
  • 與iOS8不同的是,iOS10本地通知在前台與在后台觸發通知調用的代理方法不一樣如下:


#pragma mark - delegate iOS10

// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
// 前台調用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0){
    NSLog(@"1--title---%@", notification.request.content.title);
    NSLog(@"2--subtitle---%@", notification.request.content.subtitle);
    NSLog(@"3--userInfo---%@", notification.request.content.userInfo);
    NSLog(@"4--body---%@", notification.request.content.body);
}

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.
// 后台點擊通知后調用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED{
    NSLog(@"7--title---%@", response.notification.request.content.title);
    NSLog(@"8--subtitle---%@", response.notification.request.content.subtitle);
    NSLog(@"9--userInfo---%@", response.notification.request.content.userInfo);
    NSLog(@"10--body---%@", response.notification.request.content.body);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM