Service Extension

class NotificationService: UNNotificationServiceExtension {

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

    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)
            }
        }
    }
    
    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)
        }
    }

}

你可能感兴趣的:(Service Extension)