import UserNotificationsextension UNNotificationAttachment { static func create(IDentifIEr: String,image: UIImage,options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { let fileManager = fileManager.default let tmpSubFoldername = ProcessInfo.processInfo.globallyUniqueString let tmpSubFolderURL = URL(fileURLWithPath: NstemporaryDirectory()).appendingPathComponent(tmpSubFoldername,isDirectory: true) do { try fileManager.createDirectory(at: tmpSubFolderURL,withIntermediateDirectorIEs: true,attributes: nil) let imagefileIDentifIEr = IDentifIEr+".png" let fileURL = tmpSubFolderURL.appendingPathComponent(imagefileIDentifIEr) guard let imageData = UIImagePNGRepresentation(image) else { return nil } try imageData.write(to: fileURL) let imageAttachment = try UNNotificationAttachment.init(IDentifIEr: imagefileIDentifIEr,url: fileURL,options: options) return imageAttachment } catch { print("error " + error.localizedDescription) } return nil }}
当我安排新通知时,我会像这样使用它:
// url of the image such as http://www.unsplash.com/image.pnglet data = try? Data(contentsOf: url) guard let myImage = UIImage(data: data!) else { return }if let attachment = UNNotificationAttachment.create(IDentifIEr: key,image: myImage,options: nil) { content.attachments = [attachment]}
创建这样的通知会冻结应用程序几秒钟,因为应用程序会同步下载图像.我也试过使用dispatchQueue,但它没有改变任何东西.我做错了什么?
解决方法 您的代码下载图像,解析它以创建UIImage,将图像转换回PNG数据块,然后将此数据写入临时文件.您可以跳过创建UIImage的步骤并将其转换回文件.
尝试使用URLSession和URLDataTask:
let fileURL = ...let task = URLSession.shared.dataTask(with: url) { (data,_,_) in do { try imageData.write(to: fileURL) let attachment = UNNotificationAttachment.create(IDentifIEr: key,options: nil) // call closure to call back with attachment and/or error } catch let ex { // call closure with error }}task.resume()
我遗漏了一些错误处理和其他细节,但这应该让你大致了解异步执行它需要什么. URLSessions使用GCD执行异步网络.
总结以上是内存溢出为你收集整理的ios – 将图像附加到给定图像URL的通知全部内容,希望文章能够帮你解决ios – 将图像附加到给定图像URL的通知所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)