Stories

Detail Return Return

【iOS】原生推送功能總結 - Stories Detail

iOS的推送功能有本地推送和遠程推送,此處完整描述一下本地推送的功能。當前iOS系統使用版本基本都已經超過iOS10,10以下的實現不再描述,也避免調用方法混淆。

簡介

iOS的本地推送主要有兩種用法,一種是App外推送,另一種是App內也推送。

前者可以視為後者的簡單實現,關鍵在於是否實現UNUserNotificationCenterDelegate的協議。如果不實現該協議,則只有當App不在前台的時候,推送才會出現,如果推送的時候App是打開的,則推送不會發出。

此處我們先實現App外推送,再實現App內推送及通知點擊回調功能,一步步拆分本地推送的相關功能,明確各個功能對應的模塊。

此外,調用推送功能的時候需要引入頭文件:

#import <UserNotifications/UserNotifications.h>

在使用推送相關代碼時都需提前引入該頭文件。

推送授權

要實現推送功能就需要先實現推送的授權功能,授權最好在AppDelegate的didFinishLaunchingWithOptions裏實現。如果沒有開啓通知權限,則無法進行推送。

- (void)registerAPN {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    }];
}

推送功能實現

如果只需要實現App外推送,到這裏功能就足夠了,獲取通知權限並設置推送內容。

以下為發送通知代碼:

- (void)addLocalAPNS {
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"App推送";
    //content.subtitle = @"測試通知副標題";
    content.body = @"這是一條測試通知";
    content.sound = [UNNotificationSound defaultSound];
    // 添加自定義聲音
    //content.sound = [UNNotificationSound soundNamed:@"alert.caf"];
    // 設置觸發條件(如 5 秒後)及是否重複推送
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    // 創建請求
    NSString *identifier = @"localNotification";
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    // 添加到通知中心
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"Failed to schedule notification: %@", error.localizedDescription);
        }
    }];
}

完整推送功能

要實現App開啓的時候也進行推送及獲取推送消息和點擊通知後的回調,需設置及實現UNUserNotificationCenterDelegate協議。

設置代理

代理可一樣放在didFinishLaunchingWithOptions方法處。

代理方法:

[UNUserNotificationCenter currentNotificationCenter].delegate = self;

實現協議方法

遠程推送的內容也同樣是在此處做處理,只是遠程推送正常關聯第三方比如極光等實現,此處不展開討論。

處理前台收到通知的代理方法

當App打開時,收到推送,則該方法會調用,可以解析notification參數獲取推送的內容並做對應處理。

具體代碼:

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}
  • 此處可設置通知的樣式,根據需要使用對應的UNNotificationPresentationOptions類,選擇自己想要展示的通知類型。
  • 如果不需要展示通知,也可以使用UNNotificationPresentationOptionNone作為參數傳入。

notification參數內容:

// 解析通知內容
UNNotificationContent *content = notification.request.content;
NSString *title = content.title;
NSString *body = content.body;
NSDictionary *userInfo = content.userInfo;

NSLog(@"Received Notification in foreground: %@", userInfo);
處理點擊通知之後的代理方法

當用户點擊頂部通知時,無論App在前台還是後台,該方法都會調用,此處同樣可以解析response參數獲取推送的相關信息,並做對應處理。正常點擊通知跳轉到對應的頁面和功能都是在此處處理。

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    UNNotificationContent *content = response.notification.request.content;
    NSDictionary *userInfo = content.userInfo;
    NSLog(@"User tapped on notification: %@", userInfo);
    // 自定義行為(如跳轉頁面)
    if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
        NSLog(@"Default action triggered");
        // 可以在這裏跳轉到具體頁面
    }
    completionHandler();
}

response參數內容:

// 解析通知內容
UNNotificationContent *content = response.notification.request.content;
NSDictionary *userInfo = content.userInfo;
NSLog(@"User tapped on notification: %@", userInfo);
user avatar someonelikeyou Avatar MrYU4 Avatar tiandekaixinguo Avatar manshenjiroudepingpangqiu_dw95y0 Avatar airenaodexianrenqiu Avatar segfal_coder Avatar CoolBreeze-SeclusionDream Avatar jingdongkeji Avatar mano Avatar 2022-yang Avatar wangjingyu_5f58472234cff Avatar zouzaidadaomanshihuaxiang Avatar
Favorites 12 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.