iOS 10个带图片的远程通知

iOS 10 remote notifications with pictures

首先,我是 Swift 的新开发人员,我有 Objective C 背景,但我主要是 Android 开发人员。

实际上我正在 Swift 3 和 Xcode 8 中开发一个应用程序。我需要向这个应用程序添加 Apple 新的富推送通知系统。

我已经能够添加带有图片、视频和 gif 的本地富通知示例。但我需要显示带有典型 Internet 服务器上托管的图片的远程通知。

要启动本地通知,我正在使用此代码:

@IBAction func launchPicNotification(sender: UIButton) {
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Body"
    content.sound = UNNotificationSound.default()

    let url = Bundle.main.url(forResource:"foto", withExtension: "jpg")

    let attachment = try? UNNotificationAttachment(identifier: "Notification",
                                                   url: url!,
                                                   options: [:])

    if let attachment = attachment {
        print("Yes")
        content.attachments.append(attachment)
    }else{
        print("No")
    }

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 10.0, repeats: false)
    let request = UNNotificationRequest(identifier:"identificador", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request){(error) in

        if (error != nil){

            //handle here

        }

    }
}

我需要加载远程 jpg 文件作为附加图像。有人知道如何加载远程文件而不是加载本地图片吗?

谢谢

我为 UIImage 添加了一个扩展来处理这个问题。从下载的数据创建 UIImage 后,您可以调用此函数创建本地 URL.

extension UIImage {

func createLocalURL() -> URL? {

    guard let data = UIImagePNGRepresentation(self) else {
        print("Coule not get UIImagePNGRepresentation Data for photo")
        return nil
    }

    let localUrl = self.getDocumentsDirectory().appendingPathComponent("copy.png")

    do {
        try data.write(to: localUrl)
    } catch let error {
        print("Failed to write to URL")
        print(error)
    }
    return localUrl
}

}