我需要在当前应用程序中使用图像实现丰富的通知。
我已经实现了一切,并且工作正常。并接收推送通知,但只获取标题和消息,但不获取图像作为附件
没有可变内容的正常通知正常工作。
据我测试,证书方面没有问题..我使用NotificationService扩展来显示媒体附件
有什么想法吗?
我的有效负载如下所示:
[AnyHashable("title"): New trailer released- Hindi Movies, AnyHashable("message"): Kuchh Bheege Alfaaz - Official Hindi Trailer, AnyHashable("aps"): {
alert = "New trailer released- Hindi Movies";
badge = 2;
sound = default;
}, AnyHashable("trailer_img"): uploads/trailer_image/9703831856a7968b8b5cf6b10357dc2c1.jpg]
我的NotificationService类代码如下:
class NotificationService: UNNotificationServiceExtension {
var contentHandler : ((UNNotificationContent) -> Void)?
var content : UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler:
@escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
self.content = (request.content.mutableCopy()
as? UNMutableNotificationContent)
let userInfo : [AnyHashable: Any] = request.content.userInfo
print(userInfo)
if let bca = self.content {
func save(_ identifier: String,
data: Data, options: [AnyHashable: Any]?)
-> UNNotificationAttachment? {
let directory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString,
isDirectory: true)
do {
try FileManager.default.createDirectory(at: directory,
withIntermediateDirectories: true,
attributes: nil)
let fileURL = directory.appendingPathComponent(identifier)
try data.write(to: fileURL, options: [])
return try UNNotificationAttachment.init(identifier: identifier,
url: fileURL,
options: options)
} catch {
}
return nil
}
func exitGracefully(_ reason: String = "") {
let bca = request.content.mutableCopy()
as? UNMutableNotificationContent
bca!.title = reason
contentHandler(bca!)
}
let reachability = Reachability()!
reachability.whenReachable = { reachability in
DispatchQueue.main.async {
if reachability.isReachableViaWiFi {
guard let content = (request.content.mutableCopy()
as? UNMutableNotificationContent) else {
return exitGracefully()
}
let userInfo : [AnyHashable: Any] = request.content.userInfo
print(userInfo)
guard let attachmentURL = userInfo["trailer_img"]
as? String else {
return exitGracefully()
}
guard let imageData =
try? Data(contentsOf: URL(string: "http://techindiana.com/dev/truetrailer_app/" + attachmentURL)!)
else {
return exitGracefully()
}
guard let attachment =
save("image.png", data: imageData, options: nil)
else {
return exitGracefully()
}
content.attachments = [attachment]
contentHandler(content.copy() as! UNNotificationContent)
} else {
return exitGracefully()
}
}
}
reachability.whenUnreachable = { reachability in
DispatchQueue.main.async {
return exitGracefully()
}
}
do {
try reachability.startNotifier()
} catch {
return exitGracefully()
}
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bca = self.content {
contentHandler(bca)
}
}
}