【问题标题】:UNNotificationAttachment set image URL to Caches directoryUNNotificationAttachment 设置图片 URL 到 Caches 目录
【发布时间】:2018-08-08 08:23:42
【问题描述】:

我的应用程序中有图像缓存机制。我还需要显示带有图像的本地通知。我有个问题。当我尝试使用图像设置UNNotificationAttachment 时,我会从缓存中获取图像,或者,如果图像不存在,我会下载并缓存。然后我构建了一个指向 Caches 目录的 URL,但是当我将此 URL 传递给 UNNotificationAttachment 时,我收到一个错误:NSLocalizedDescription=Invalid attachment file URL。我做错了什么?

if let diskUrlString = UIImageView.sharedImageCache.diskUrlForImageUrl(imageUrl) {
    if let diskUrl = URL(string: diskUrlString) {
       do {
            res = try UNNotificationAttachment(identifier: imageUrlString, url: diskUrl, options: nil)
        } catch (let error) {
            print("error", error)
            // Invalid attachment file URL
        }
    }
}

func diskUrlForImageUrl(_ imageUrl: URL) -> String? {
    let urlRequest = URLRequest(url: imageUrl)
    return ImageCache.cacheDirectory.appending("/\(ImageCache.imageCacheKeyFromURLRequest(urlRequest))")
}

static fileprivate var cacheDirectory: String = { () -> String in
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
    let res = documentsDirectory.appending("/scAvatars")
    let isExist = FileManager.default.fileExists(atPath: res, isDirectory: nil)
    if !isExist {
        try? FileManager.default.createDirectory(atPath: res, withIntermediateDirectories: true, attributes: nil)
    }
    return res
}()

【问题讨论】:

    标签: ios swift unnotificationrequest unnotificationattachment


    【解决方案1】:

    我发现如果我在diskUrlString 中添加前缀file:///private,那么URL 会像预期的那样构建。但我仍然不明白,如何在不硬编码此前缀的情况下构建 url。所以现在我可以同时使用缓存和UNNotificationAttachment

    【讨论】:

      【解决方案2】:

      这里的问题是您使用的是 路径,而不是 URL。路径是一个字符串,例如“/var/log/foo.log”。 URL 在语义上比路径更复杂。您需要一个描述图像文件在设备文件系统上的位置的 URL。

      为图像文件构建一个正确构建的 URL,附件可能会起作用。附件可能还需要一个类型标识符提示来告诉 iOS 文件中的数据类型。

      【讨论】:

        【解决方案3】:

        您不必使用网址。您可以通过UNNotificationAttachment 使用图像数据。

        这是一个示例代码。

        let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
        let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
                    
        let imageURL = URL(fileURLWithPath: paths.first!).appendingPathComponent("\(fileName).jpg")
        let image = UIImage(contentsOfFile: imageURL.path)
        let imageData = image?.pngData()
        
                    
        if let unwrappedImageData = imageData, let attachement = try? UNNotificationAttachment(data: unwrappedImageData, options: nil) {
            content.attachments = [attachement]
        }
        

        【讨论】:

          猜你喜欢
          • 2017-12-26
          • 1970-01-01
          • 2012-02-05
          • 2012-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多