У меня проблема с уведомлением Apple Pu sh. Когда экран iPhone заблокирован, Rich Notification не отображает изображения, поступающие в APNS Payload. однако он отлично работает, если телефон разблокирован.
Кроме того, мы получаем несколько уведомлений одновременно с тем, что загрузка изображения прекратилась после 2-3 уведомлений.
final class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
if let attachmentMedia = bestAttemptContent.userInfo["URL"] as? String {
let mediaUrl = URL(string: attachmentMedia)
let LPSession = URLSession(configuration: .default)
LPSession.downloadTask(with: mediaUrl!, completionHandler: { temporaryLocation, response, error in
if let err = error {
print("Leanplum: Error with downloading rich push: \(String(describing: err.localizedDescription))")
contentHandler(bestAttemptContent);
return;
}
let fileType = self.determineType(fileType: (response?.mimeType)!)
let fileName = temporaryLocation?.lastPathComponent.appending(fileType)
let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName!)
do {
try FileManager.default.moveItem(at: temporaryLocation!, to: temporaryDirectory)
let attachment = try UNNotificationAttachment(identifier: "", url: temporaryDirectory, options: nil)
bestAttemptContent.attachments = [attachment];
contentHandler(bestAttemptContent);
// The file should be removed automatically from temp
// Delete it manually if it is not
if FileManager.default.fileExists(atPath: temporaryDirectory.path) {
try FileManager.default.removeItem(at: temporaryDirectory)
}
} catch {
print("Leanplum: Error with the rich push attachment: \(error)")
contentHandler(bestAttemptContent);
return;
}
}).resume()
}
handleContent(bestAttemptContent: bestAttemptContent, request: request)
}
}
// MARK: - Leanplum Rich Push
func determineType(fileType: String) -> String {
// Determines the file type of the attachment to append to URL.
if fileType == "image/jpeg" {
return ".jpg";
}
if fileType == "image/gif" {
return ".gif";
}
if fileType == "image/png" {
return ".png";
} else {
return ".tmp";
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
func handleContent(bestAttemptContent: UNMutableNotificationContent, request: UNNotificationRequest) {
if let transactionMessage = bestAttemptContent.userInfo[NotificationPayloadKeys.transactionMessage] as? String {
bestAttemptContent.title = bestAttemptContent.body
bestAttemptContent.body = transactionMessage
}
guard let mediaAttachment = request.mediaAttachment else { return }
bestAttemptContent.attachments = [mediaAttachment]
}
extension UNNotificationRequest {
var mediaAttachment: UNNotificationAttachment? {
guard let attachmentURL = content.userInfo[NotificationPayloadKeys.multimediaUrl] as? String,
let url = URL(string: attachmentURL),
let imageData = try? Data(contentsOf: url) else {
return nil
}
return try? UNNotificationAttachment(gifData: imageData, options: nil)
}
}
extension UNNotificationAttachment {
convenience init(gifData: Data, options: [NSObject: AnyObject]?) throws {
let fileManager = FileManager.default
let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString
let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true)
try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil)
let imageFileIdentifier = UUID().uuidString + ".gif"
let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier)
try gifData.write(to: fileURL)
try self.init(identifier: imageFileIdentifier, url: fileURL, options: options)
}
}
Заранее спасибо.