iOS 10 UserNotifications 實踐

簡介

在 iOS 10 中新加入 UserNotifications 框架,對以往雜亂無章的通知系統 API 進行了統一,更方便開發者們快速引用。關于新框架的一些基本概念在喵大《iOS 10 UserNotifications 框架解析》中已有詳細的描述,本文只對實踐中的具體運用做介紹。

基本流程

iOS 10中通知相關操作遵循下面的流程:


流程.png

權限申請

iOS 各個版本 Notifications 權限申請代碼如下:

// iOS 10 support
if #available(iOS 10.0, *) {
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    UNUserNotificationCenter.current().requestAuthorization(options: options) { granted, error in
        if granted {
           // 用戶允許進行通知
        }
    }
}
// iOS 9 support
else if #available(iOS 9, *) {
    let types: UIUserNotificationType = [.alert, .sound, .badge]
    let settings = UIUserNotificationSettings(types: types, categories: nil)
    UIApplication.shared.registerUserNotificationSettings(settings)
    // ...其他操作
    if UIApplication.shared.currentUserNotificationSettings?.types != [] {
        // 用戶允許進行通知
    }
} 
// iOS 8 support
else if #available(iOS 8, *) {
    let types: UIUserNotificationType = [.alert, .sound, .badge]
    let settings = UIUserNotificationSettings(types: types, categories: nil)
    UIApplication.shared.registerUserNotificationSettings(settings)
    // ...其他操作
    if UIApplication.shared.currentUserNotificationSettings?.types != [] {
        // 用戶允許進行通知
    }
} 
// iOS 7 support
else {
    let types: UIRemoteNotificationType = [.badge, .sound, .alert]
    UIApplication.shared.registerForRemoteNotifications(matching: types)
}

注冊Token

當用戶同意授權以后,還需要向系統注冊一個 Device Token,并將這個 token 發送到 APNs(Apple Push Notification Service),然后 APNs 通過 token 識別設備和應用,并通知推送給用戶。

// 向 APNs 請求 token
UIApplication.shared.registerForRemoteNotifications()

// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("APNs device token: \(tokenString)")
    // 上傳至后臺服務器
}

// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
    // Print the error to console (you should alert the user that registration failed)
    print("APNs registration failed: \(error)")
}

發送推送通知

關于 APNs 的推送原理 就不做詳細說明,這里以 Node.js 為例子搭建推送測試工具,步驟如下:
1、創建 APNs 服務的訪問 Auth Key ID

創建key.png

2、獲取 Key ID,點擊 Download 同時下載 .p8 證書文件
獲取key.png

3、獲取開發者賬號的 Team ID
Membership.png

4、編寫測試腳本 push.js,內容如下:

var apn = require('apn');

if (process.argv.length == 3) {
    // Enter the device token
    var deviceToken = process.argv[2];

    // Set up apn with the APNs Auth Key
    var apnProvider = new apn.Provider({  
         token: {
            key: 'xxxx.p8', // Path to the key p8 file
            keyId: 'xxxx',
            teamId: 'xxxx',
        },
        production: false // Set to true if sending a notification to a production iOS app
    });

    // Prepare a new notification
    var notification = new apn.Notification();

    // Specify your iOS app's Bundle ID (accessible within the project editor)
    notification.topic = 'com.domain.xxxx';

    // Set expiration to 1 hour from now (in case device is offline)
    notification.expiry = Math.floor(Date.now() / 1000) + 3600;

    // Set app badge indicator
    notification.badge = 1;

    // Play ping.aiff sound when the notification is received
    notification.sound = 'default';

    // Display the following message (the actual notification text, supports emoji)
    notification.alert = 'Hello World \u270C';

    // Send any extra payload data with the notification which will be accessible to your app in didReceiveRemoteNotification
    notification.payload = {id: 123};

    // Actually send the notification
    apnProvider.send(notification, deviceToken).then(function(result) {  
        // Check the result for any failed devices
        console.log(result);
    });
} else {
    console.log("Usage: node push.js <deviceToken>");
}

至此就可以測試遠程推送通知了。當然還可以其他類似的工具 NWPusher

node push.js 8c6f8b7056613a5223c690fb171697c524173b9c39e7dff688c66f0b23fbefdb

展示處理

iOS 10以前通知完全是系統行為,開發者無法自主控制,引入 UserNotifications 框架以后通知數據處理流程如下:

Notification Extension.png

其中 Service Extension 和 Content Extension 前者可以讓我們有機會在收到遠程推送的通知后,展示之前對通知內容進行修改;后者可以用來自定義通知視圖UI的樣式。尤其是Service Extension收到通知以后必執行,iOS平臺終于可以做更精準的推送到達率統計了
1、創建 Service Extension,Xcode 會自動生成模板代碼。在這里可以進行埋點統計,并在通知中展示多媒體文件(圖片/音頻/視頻)。

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    /**
     該方法可以在限定時間內(30秒)修改請求中的 content 內容,然后返回給系統顯示
     */
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            // 進行 Push 到達的埋點統計
            var msgid = 1
            if let tmp = bestAttemptContent.userInfo["msgid"] as? NSNumber {
                msgid = tmp.intValue
            }
            tracePush(msgId: msgId)

            /** 
                添加多媒體附件
                內置資源支持10MB以內圖片,50M以內音視頻
                外鏈支持30秒內能下載完成的多媒體文件
             */ 
            if let imageURLString = bestAttemptContent.userInfo["image"] as? String, let URL = URL(string: imageURLString) {
                downloadAndSave(url: URL) { localURL in
                    if let localURL = localURL {
                       do {
                          let attachment = try UNNotificationAttachment(identifier: "image_downloaded", url: localURL, options: nil)
                          bestAttemptContent.attachments = [attachment]
                       } catch {
                          print(error)
                       }
                    }
                    contentHandler(bestAttemptContent)
                }
            } else {
                contentHandler(bestAttemptContent)
            }
        }
    }

    /**
     一定時間內(30秒)沒將內容返回給系統,則會自動調用該方法,未完成的修改將被忽略
     */
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

2、創建 Content Extension,Xcode 會自動生成模板代碼(若不需要自定義UI,可跳過本部分)。iOS 10中通知分類注冊方式更加簡潔,通知響應處理方式也集中到了獨立的 delegate中,包括本地和遠程通知的處理。

func registerNotificationCategory() {
    if #available(iOS 10.0, *) {
       UNUserNotificationCenter.current().setNotificationCategories(createiOS10Category())
       UNUserNotificationCenter.current().delegate = notificationHandler
    } else {
       let types: UIUserNotificationType = [.alert, .sound, .badge]
       let settings = UIUserNotificationSettings(types: types, categories: createiOS89Category())
       UIApplication.shared.registerUserNotificationSettings(settings)
    }
}

// 當 application 處于前臺活躍狀態時會被調用,控制是否需要彈出提示
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound, .badge])
}

// 當用戶點擊通知啟動 application,前臺活躍狀態點擊通知時都會被調用到
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
}

Content Extension 也可以在 application 未啟動前,處理已注冊過的通知分類

// 用戶每收到一條通知都會執行一次調用
func didReceive(_ notification: UNNotification)  {

}

// 用戶點擊通知時會調用
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Swift.Void) {

}

3、編輯推送信息,簡單的示例 payload 如下:

{
  "msgid": 100,
  "aps":{
    "alert":{
      "title":"Image Notification",
      "body":"Show me an image from web!"
    },
    "mutable-content":1
  },
  "image": "https://onevcat.com/assets/images/background-cover.jpg"
}

詳細定義參見 蘋果官方文檔
4、Service Extension 和 Content Extension 都有獨立的 Bundle ID,打包時需要進行簽名,同時也需要配置 ATS

ATS.png

注意事項:

1、mutable-content 表示接收到通知時會對內容進行修改,必須配置為1,否則不會執行 Service Extension。
2、附件可以設置多個 attachment 實例,但系統默認只會顯示第一個,當然可以通告代碼修改它們的順序,以顯示最符合情景的圖片或者視頻。
3、extension 的 bundle 和 app main bundle 并不相同,屬于不同的沙盒目錄,也就是說當要使用內置資源時需添加進 extension 的 bundle 中。
4、如果使用的圖片和視頻文件不在 bundle 內部,它們將被移動到系統的負責通知的文件夾下,然后在當通知被移除后刪除。如果媒體文件在 bundle 內部,它們將被復制到通知文件夾下。每個應用能使用的媒體文件的文件大小總和是有限制,超過限制后創建 attachment 時將拋出異常,即不能同時創建太多的 attachment。
5、當訪問一個已經創建好的 attachment 時,需使用startAccessingSecurityScopedResource來獲取訪問權限:

let content = notification.request.content
if let attachment = content.attachments.first {  
    if attachment.url.startAccessingSecurityScopedResource() {  
       eventImage.image = UIImage(contentsOfFile: attachment.url.path!)
      attachment.url.stopAccessingSecurityScopedResource()  
    }  
}  

關于 Service Extension、Content Extension 和多媒體通知的使用,可以參考 Demo。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容