iOS10 rich push notification 带图通知 趟坑记录

参考链接

1、活久见的重构 - iOS 10 UserNotifications 框架解析 -- OneV's Den
2、iOS10推送通知进阶(Notification Extension)
3、Push Debugging Guide - iOS


结果展示

只实现如图的效果,只添加一个 Notification Service Extension: 通知服务扩展 即可。

带图通知.jpg


具体实现

1、File -> New -> Target


image.png

2、配置相关


Automatically manage signing

Automatically manage signing 还是第一选择,如果需要手动配置:

  • Bundle Identifier: 要以 “主App的Bundle Identifier ”为前缀。
  • Signing:
    App ID:要独立于主App有Target自己的App ID
    Certificate:要独立于主App有Target自己的Certificate
    Provisioning Profile: 要独立于主App有Target自己的Provisioning Profile

3、代码实现

NotificationService.swift

import UserNotifications

class NotificationService: UNNotificationServiceExtension {

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

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            if let imageURL = bestAttemptContent.userInfo["media-url"] {
                if let urlString = imageURL as? String {
                    carnivalHandleAttachmentDownload(content: bestAttemptContent.userInfo, urlString: urlString)
                }
            } else {
                contentHandler(bestAttemptContent)
                return
            }
        }
    }
    
    func carnivalHandleAttachmentDownload(content: [AnyHashable : Any], urlString: String) {
        guard let url = URL(string: urlString) else {
            self.contentHandler!(self.bestAttemptContent!)
            return
        }
        
        self.downloadTask = URLSession.shared.downloadTask(with: url) { (location, response, error) in
            if let location = location {
                let tmpDirectory = NSTemporaryDirectory()
                let tmpFile = "file://".appending(tmpDirectory).appending(url.lastPathComponent)
                let tmpUrl = URL(string: tmpFile)!
                try! FileManager.default.moveItem(at: location, to: tmpUrl)
                
                if let attachment = try? UNNotificationAttachment(identifier: "image", url: tmpUrl) {
                    self.bestAttemptContent?.attachments = [attachment]
                }
            }
            self.contentHandler!(self.bestAttemptContent!)
        }
        self.downloadTask?.resume()
    }
    
    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)
        }
    }

}

4、info.plist 配置

  • 趟坑记录一: "media-url": "https://i.imgur.com/t4WGJQx.jpg" ,如果你的图片没法展示,请确认图片链接是否是http://的,支持Http需要如下图配置。
    ERROR:App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
默认不支持http,需要如图配置

5、参数解析:

  • 通过APNs我们发送或收到的数据格式长这样:
{
    "aps": {
        "alert": {
            "body": "Push notification body",
            "title": "Push notification title"
        },
        "mutable-content": 1            //  1 表示可变内容,即支持Notification Service Extension, 0表示不支持
        //  "category": "rich-apns"     // 自定义push notification UI,另一个Notification Content Extension支持的
    },
    "media-url": "https://i.imgur.com/t4WGJQx.jpg"   // 这些是自定义的,可以在你的Extension解析
}

Debug in NotificationServiceExtension

?: 你会发现你没办法在“Target: NotificationServiceExtension”的 NotificationService.swift 中断点Debug

  • 其实你要做到以下几点
    1、在开发环境支持发通知:
    开发环境的push证书.png

    2、Run “Target: NotificationServiceExtension” 而不是主App。
    3、在开发环境发通知给自己:如下文的推送测试工具部分,“gateway.sandbox.push.apple.com”就是Apple提供给开发者在Debug环境发通知的服务。

推送测试工具:

Easy APNs Provider 亲测好用

Easy APNs Provider.png

使用界面.png

你可能感兴趣的:(iOS10 rich push notification 带图通知 趟坑记录)