Вы можете использовать Notification Service Extension
для Push-уведомлений с изображением.Это новая функция от iOS10.Подробнее здесь .
Шаги:
Укажите URL-адрес изображения в полезной нагрузке push-уведомлений, например:
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"image_url" : "http://host_name/image.png",
}
Отправка push-уведомлений
После получения push-уведомления Notification Service Extension
активируется перед отображением баннера уведомления, поэтому изображение загружаетсяи сохраняются в области tmp с использованием URL-адреса в полезной нагрузке
Отображается уведомление с изображением
Реализация Notification Service Extension
Добавить Notification Service Extension
File > New > Target
в меню Xcode
iOS > Application Extension > Notification Service Extension
NotificationService.swift
создал.
Реализация
func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)
Вот пример кода:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard let imageUrl = request.content.userInfo["image_url"] as? String else {
if let bestAttemptContent = self.bestAttemptContent {
contentHandler(bestAttemptContent)
}
return
}
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { (data, response, error) in
do {
if let tempImageFilePath = NSURL(fileURLWithPath:NSTemporaryDirectory())
.appendingPathComponent("tmp.jpg") {
try data?.write(to: tempImageFilePath)
if let bestAttemptContent = self.bestAttemptContent {
let attachment = try UNNotificationAttachment(identifier: "id", url: tempImageFilePath, options: nil)
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}
} else {
// error: writePath is not URL
if let bestAttemptContent = self.bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
} catch _ {
// error: data write error or create UNNotificationAttachment error
if let bestAttemptContent = self.bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
})
task.resume()
}
Это позволяет вашему приложению загрузить изображение из image _ url
в Payload и прикрепить его кPush-уведомление.