iOS 10新的通知机制中添加图片的方法详解
程序员文章站
2023-12-20 08:11:46
1、新建target
2、实现unnotificationserviceextension
我这里用的是swift
//
// notificati...
1、新建target
2、实现unnotificationserviceextension
我这里用的是swift
// // notificationservice.swift // notificationserviceextension // // created by heyuan li on 17/2/26. // copyright © 2017年 fenbi. all rights reserved. // import usernotifications 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 { // modify the notification content here... bestattemptcontent.title = "上课啦" 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) } } } } 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) } } 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 ext = (url.absolutestring as nsstring).pathextension let cachedirs = filemanager.default.urls(for: .cachesdirectory, in: .userdomainmask) if cachedirs.count > 0 { let cachedir = cachedirs[cachedirs.count - 1] /// todo tutor cache /// todo md5 extension let url = cachedir.appendingpathcomponent("123").appendingpathextension(ext) if let _ = try? data.write(to: url) { localurl = url } } } handler(localurl) }) task.resume() } }
3、发push的时候,加上”mutable-content”: 1
{ "aps": { "alert": "instant message from crm", "sound": "default", "mutable-content": 1 }, ...... "image": "https://g0.fbcontent.cn/api/tutor/images/153c6c68411747f.jpg" }
这个很关键
最后运行,就会自动展示图片啦。
需要说明的是,默认是只能https的,如果想显示http图片,需要自行设定ats相关配置。
总结
以上就是这篇文章的全部内容了,希望本文的内容对各位ios开发者们能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。