Just My Life & My Work

自從iOS10開始,Apple整合並重構原本復雜的SDK,特別是本地推播 (Local Notification)遠程推播 (Remote Notification),已經統合為專門處理的User Notifications Framework

五年前(不小心透露年齡⋯⋯)我已介紹過Local Notification,文章可見:Remote/Local Notification

整合過後,推播變得更好管理,於是我們要逐漸捨既舊有的實作習慣囉~

[iOS] Local Notification (本地推播).PNG

我的本地推播展示,只要寫在AppDelegate.m即可,我的目的是想要在App進入背景後,推播通知使用者,要盡快回到App,讓傳輸資料持續進行不中斷。

首先必須引用:

#import <UserNotifications/UserNotifications.h>

/**
 Theme: User Notifications Demo
 IDE: Xcode 9
 Language: Objective C
 Date: 107/07/23
 Author: HappyMan
 Blog: https://cg2010studio.com/
 */

#import 

// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 使用 UNUserNotificationCenter 來管理通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    // 監聽回調事件
    center.delegate = self;

    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    // Enable or disable features based on authorization.
        if (granted == YES) {
            NSLog(@"通知接受授權V");
        }
        else {
            NSLog(@"通知拒絕授權X");
        }
    }];

    // 獲取當前的通知設置
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"Notification Settings: %@", settings);
    }];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    [self registerNotificationAfterSecond:5];

}

-(void)registerNotificationAfterSecond:(NSInteger)time
{
    // 使用 UNUserNotificationCenter 來管理通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

    // 建立一個包含待通知內容的 UNMutableNotificationContent 對象
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"提示" arguments:nil];
    content.subtitle = [NSString localizedUserNotificationStringForKey:@"資料傳輸中⋯⋯" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"請回到[快樂健康2.0]\nApp保持前景且螢幕常亮" arguments:nil];
    content.sound = [UNNotificationSound defaultSound];

    NSURL *imageURL = [[NSBundle mainBundle] URLForResource:@"logo" withExtension:@"png"];
    NSError *error;
    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"HappyAttachment" URL:imageURL options:nil error:&error];
    content.attachments = @[attachment];

    // 在 time 後推送本地推播
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"HappyRequest" content:content trigger:trigger];

    // 新增推播成功後的處理
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功增加推播" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:okAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    }];
}

特別列印出來:

Notification Settings: <UNNotificationSettings: 0x1c009b030; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: NotSupported, lockScreenSetting: Enabled, carPlaySetting: NotSupported, alertSetting: Enabled, alertStyle: Banner>

可知道當前使用者授權哪些推播權限。

除了Title、Subtitle和Body,我還有加入一張圖片~

[iOS] Local Notification (本地推播)2.jpg

推播通知不只是上述提到的這幾項功能,可是卻是最常使用的部分。其它還有在推播通知介面下面產生按鈕推播通知的刪除與修改等等較為進階的功能。之後有需要再來研究吧!

參考:

廣告

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: