【发布时间】:2018-07-30 15:57:14
【问题描述】:
我正在尝试使用 Xcode、Swift3 创建 iOS 富推送通知。 我已经使用 php 的 curl 命令确定了推送通知(主题、正文),但我无法创建引用 in this document 的丰富推送通知。
我添加了这样的通知服务扩展:「 File 」→「 New 」→「 Target... 」→「 Notification Service Extension 」,并且我还添加了「'mutable_content': True」 curl 命令。
然后运行但不调用「class NotificationService: UNNotificationServiceExtension」,因此无法查看推送通知图像。
下面是我的代码
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
let imageKey = AnyHashable("gcm.notification.image_url")
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 imageUrl = request.content.userInfo[imageKey] as? String {
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { [weak self] (data, response, error) in
if let data = data {
do {
let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("push.png")
try data.write(to: writePath)
guard let wself = self else {
return
}
if let bestAttemptContent = wself.bestAttemptContent {
let attachment = try UNNotificationAttachment(identifier: "nnsnodnb_demo", url: writePath, options: nil)
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}
} catch let error as NSError {
print(error.localizedDescription)
guard let wself = self else {
return
}
if let bestAttemptContent = wself.bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
} else if let error = error {
print(error.localizedDescription)
}
})
task.resume()
} else {
if let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
【问题讨论】:
标签: ios xcode swift3 unnotificationserviceextension rich-notifications