我正尝试在一段时间后(例如 10 秒)发送本地通知。我想向来自 xcassets 的通知添加图像,但 imageURL
始终为 nil
。
我已经尝试创建一个路径,然后从该路径创建一个 URL。我还尝试使用 forResource
参数创建一个 url = nil
以便它找到任何以 "png"
作为扩展名的图像并且仍然- 无
。
let content = UNMutableNotificationContent()
content.title = "Notification title"
content.subtitle = "notification subtitle"
content.body = "notification body"
let imageName = "delete"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else {return}
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "notification.id.01", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
我添加了 print
语句以查看会发生什么,并且我已确认我的方法在 guard
语句处返回。
最佳答案
图像可以位于两个位置之一: Assets 目录或 bundle 。
当你说
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else {return}
您正在查找 bundle 中的图片。
但是你自己告诉我们,那不是图像所在的地方!它在 Assets 目录中。
这就是为什么在包中查找它失败的原因。它不在那里。
关于ios - 从 xcassets 中的图像创建 URL 总是返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603627/