I added 'Notification Service Extension' in my project, and want to show image on push notification.
In code, first I downloaded the image from the url with 'downloadTask' method of URLSessionDownloadTask
.
And it was saved successfully in the url like
'file://private/var/mobile/Containers/Data/..../tmp/CFNetworkDownload_fads.tmp'
I don't know exactly what I have to do after saving image.
After I downloaded the image successfully and saved in tmp directory, I tried with some options.
First, I made a UNNotificationAttachment
instance without any options.
Result is fail, I think it couldn't know about attachment's type. So it couldn't do right things.
Second, I made a same instance with options, I took the Uniform Type Identifier value "public.jpeg" to the key 'UNNotificationAttachmentOptionsTypeHintKey
'.
It was success but I have some curious thing. I write about it after explain third try.
Third, I tried with only change the value from "public.jpeg" to "public.png"
It was success too.
The thing I wondered is why the second and third tries were success.
They show image regardless of it's actual image format type.(jpeg, png)
I took the option as "public.jpeg", and I send a url end with '.png' extension, but it shows that image successfully.
The opposite was also success.
I don't have knowledge about image format type, so I can't understand why it works.
I would appreciate your explanation.
// Download image
guard let url = URL(string: urlString) else {
completion(nil, NSError(domain: "error", code: -1, userInfo: nil))
return
}
let task = URLSession.shared.downloadTask(with: url, completionHandler: { url, _, error in
completion(url, error)
})
task.resume()
// Make UNNotificationAttachment with option (TypeHintKey: "public.png")
if let imageAttachment = try? UNNotificationAttachment(identifier: "image", url: url, options: [UNNotificationAttachmentOptionsTypeHintKey: "public.png"]) {
mutableContent.attachments = [imageAttachment]
contentHandler(mutableContent)
} else {
contentHandler(mutableContent)
}
// Make UNNotificationAttachment with option (TypeHintKey: "public.jpeg")
if let imageAttachment = try? UNNotificationAttachment(identifier: "image", url: url, options: [UNNotificationAttachmentOptionsTypeHintKey: "public.jpeg"]) {
mutableContent.attachments = [imageAttachment]
contentHandler(mutableContent)
} else {
contentHandler(mutableContent)
}
// Make UNNotificationAttachment without option
if let imageAttachment = try? UNNotificationAttachment(identifier: "image", url: url, options: nil) {
mutableContent.attachments = [imageAttachment]
contentHandler(mutableContent)
} else {
contentHandler(mutableContent)
}