gpt4 book ai didi

ios - 将图像附加到给定图像 URL 的通知

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:00 24 4
gpt4 key购买 nike

我想在给定图像 URL 的情况下将图像附加到我的本地通知。这是创建附件的扩展:

import UserNotifications

extension 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.png
let 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]
}

enter image description here

创建这样的通知会使应用程序卡住几秒钟,因为应用程序会同步下载图像。我也尝试过使用 DispatchQueue 但它没有改变任何东西。我做错了什么?

最佳答案

您的代码下载图像,解析它以创建 UIImage,将图像转换回 PNG 数据 block ,然后将此数据写入临时文件。

您可以跳过创建 UIImage 并将其转换回文件的步骤。

尝试使用 URLSessionURLDataTask:

let fileURL = ...
let task = URLSession.shared.dataTask(with: url) { (data, _, _) in
do {
try imageData.write(to: fileURL)
let attachment = UNNotificationAttachment.create(identifier: key, image: myImage, options: nil)
// call closure to call back with attachment and/or error
}
catch let ex {
// call closure with error
}
}
task.resume()

我遗漏了一些错误处理和其他细节,但这应该让您大致了解异步执行它需要什么。 URLSession 使用 GCD 执行异步网络。

关于ios - 将图像附加到给定图像 URL 的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com