我想将 Assets.xcassets 中的图像附加到通知中。我一直在寻找解决方案大约一个小时,这似乎是唯一的方法:
func createLocalUrl(forImageNamed name: String) -> URL? {
let fileManager = FileManager.default
let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let url = cacheDirectory.appendingPathComponent("\(name).png")
guard fileManager.fileExists(atPath: url.path) else {
guard
let image = UIImage(named: name),
let data = UIImagePNGRepresentation(image)
else { return nil }
fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
return url
}
return url
}
来源:Can I get a NSURL from an XCAssets bundle?
这似乎有点矫枉过正。但是据我所知,这是获取您可以使用的 URL 的唯一方法:
let imageURL = createLocalUrl(forImageNamed: "TestImage")
let attachment = try! UNNotificationAttachment(identifier: "image", url: imageURL!, options: [:])
content.attachments = [attachment]
有没有更好的方法将 Assets.xcassets 中的图像添加到本地通知? (是的,我知道我可以将图像存储在 Assets 之外并使用 Bundle.main.etc)
Best Answer-推荐答案 strong>
我知道这是个老问题,但我稍微改进了你的解决方案,也许有人会使用它
extension UIImage {
func createLocalURL() -> URL? {
guard let imageName = self.accessibilityIdentifier else {
return nil
}
let fileManager = FileManager.default
guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
return nil
}
let url = cacheDirectory.appendingPathComponent("\(imageName).png")
guard fileManager.fileExists(atPath: url.path) else {
guard let data = self.pngData() else { return nil }
fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
return url
}
return url
}
}
你想用的时候上课
func createImageAttachment(image: UIImage?) -> [UNNotificationAttachment] {
var notificationAttachment: [UNNotificationAttachment] = []
if let image = image,
let imageUrl = image.createLocalURL(),
let attachment = try? UNNotificationAttachment(identifier: "image", url: imageUrl, options: nil) {
notificationAttachment.append(attachment)
}
return notificationAttachment
}
并将图像添加到通知中
let image = UIImage(named: "TestImage")
content = createImageAttachment(image: image)
这样更安全
关于ios - 有没有比这更好的方法在通知附件中使用来自 Assets.xcassets 的图像?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/51488589/
|