Swift

Swift – UserNotifications框架使用详解6(ServiceExtension、多媒体内容推送)

import UserNotifications
 
class NotificationService: UNNotificationServiceExtension {
 
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
 
    //我们可以在后台处理接收到的推送,让后传递修改后的的内容给contentHandler进行展示
    override func didReceive(_ request: UNNotificationRequest,
        withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
         
        if let bestAttemptContent = bestAttemptContent {
            //给通知内容添加个小尾巴
            bestAttemptContent.body = "\(bestAttemptContent.body) 【来自hangge.com】"
             
            contentHandler(bestAttemptContent)
        }
    }
     
    //如果我们获取消息后一段时间内没有调用 contentHandler 的话,系统会调用这个方法
    override func serviceExtensionTimeWillExpire() {
        //如果消息没处理好,我们也将这个没处理完毕的消息进行展示
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

原文出自:www.hangge.com  转载请保留原文链接:https://www.hangge.com/blog/cache/detail_1852.html
{
    "aps": {
        "alert": {
            "title": "最新资讯",
            "body": "2017全国文明城市公布"
        },
        "sound": "default",
        "badge": 1,
        "mutable-content": 1
    },
}
import UIKit
import UserNotifications
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //设置推送内容
        let content = UNMutableNotificationContent()
        content.title = "hangge.com"
        content.body = "囤积iPhoneX的黄牛赔到怀疑人生?"
         
        //给通知添加图片附件
        if let imageURL = Bundle.main.url(forResource: "image", withExtension: "png"),
            let attachment = try? UNNotificationAttachment(identifier: "imageAttachment",
                                                           url: imageURL, options: nil) {
            content.attachments = [attachment]
        }
         
        //设置通知触发器
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
         
        //设置请求标识符
        let requestIdentifier = "com.hangge.testNotification"
         
        //设置一个通知请求
        let request = UNNotificationRequest(identifier: requestIdentifier,
                                            content: content, trigger: trigger)
         
        //将通知请求添加到发送中心
        UNUserNotificationCenter.current().add(request) { error in
            if error == nil {
                print("Time Interval Notification scheduled: \(requestIdentifier)")
            }
        }
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

原文出自:www.hangge.com  转载请保留原文链接:https://www.hangge.com/blog/cache/detail_1852.html
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()
    }
}
{
    "aps": {
        "alert": {
            "title": "最新资讯",
            "body": "2017全国文明城市公布"
        },
        "sound": "default",
        "badge": 1,
        "mutable-content": 1
    },
    "image": "https://img1.gtimg.com/ninja/2/2017/05/ninja149447456097353.jpg"
}
import UserNotifications
 
class NotificationService: UNNotificationServiceExtension {
     
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
     
    //我们可以在后台处理接收到的推送,让后传递修改后的的内容给contentHandler进行展示
    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 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: "download",
                                                                          url: localURL,
                                                                          options: nil)
                            bestAttemptContent.attachments = [attachment]
                        } catch {
                            print(error)
                        }
                    }
                    contentHandler(bestAttemptContent)
                }
            }
        }
    }
     
    //如果我们获取消息后一段时间内没有调用 contentHandler 的话,系统会调用这个方法
    override func serviceExtensionTimeWillExpire() {
        //如果消息没处理好,我们也将这个没处理完毕的消息进行展示
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
     
    //将图片下载到本地临时文件夹中
    private func downloadAndSave(url: URL, handler: @escaping (_ localURL: URL?) -> Void) {
        let task = URLSession.shared.dataTask(with: url, completionHandler: {
            data, res, error in
            var localURL: URL? = nil
            if let data = data {
                //取得当前时间的时间戳
                let timeInterval = Date().timeIntervalSince1970
                let timeStamp = Int(timeInterval)
                //文件后缀
                let ext = (url.absoluteString as NSString).pathExtension
                let temporaryURL = FileManager.default.temporaryDirectory
                let url = temporaryURL.appendingPathComponent("\(timeStamp)")
                    .appendingPathExtension(ext)
                 
                if let _ = try? data.write(to: url) {
                    localURL = url
                }
            }
            handler(localURL)
        })
        task.resume()
    }
}

原文出自:www.hangge.com  转载请保留原文链接:https://www.hangge.com/blog/cache/detail_1852.html