【问题标题】:iOS 10 remote notifications with picturesiOS 10 带图片的远程通知
【发布时间】:2016-10-10 15:19:32
【问题描述】:

首先我是使用 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 文件作为附件。有人知道如何加载远程文件而不是加载本地图片吗?

谢谢

【问题讨论】:

  • let url = URL(string: "https://.....jpg") 呢?或者 url 必须指向本地文件。如果是这样,我想你需要先下载文件
  • 我试过了,也许我需要先下载它,你告诉我的。你能给我推荐一个在 Swift 3 上下载图片的好教程吗?谢谢。
  • @gabicuesta 您需要先下载文件才能在通知中显示图像..

标签: ios swift3 rich-notifications


【解决方案1】:

我为 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
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多