菜鸟教程小白 发表于 2022-12-11 19:48:22

ios - UNNotificationAttachment 设置图片 URL 到 Caches 目录


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

<pre><code>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(&#34;error&#34;, error)
            // Invalid attachment file URL
      }
    }
}

func diskUrlForImageUrl(_ imageUrl: URL) -&gt; String? {
    let urlRequest = URLRequest(url: imageUrl)
    return ImageCache.cacheDirectory.appending(&#34;/\(ImageCache.imageCacheKeyFromURLRequest(urlRequest))&#34;)
}

static fileprivate var cacheDirectory: String = { () -&gt; String in
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
    let res = documentsDirectory.appending(&#34;/scAvatars&#34;)
    let isExist = FileManager.default.fileExists(atPath: res, isDirectory: nil)
    if !isExist {
      try? FileManager.default.createDirectory(atPath: res, withIntermediateDirectories: true, attributes: nil)
    }
    return res
}()
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我发现,如果我在 <code>diskUrlString</code> 中添加前缀 <code>file:///private</code>,那么 URL 会像预期的那样构建。但我仍然不明白,如何在不硬编码此前缀的情况下构建 url。所以现在我可以同时使用缓存和 <code>UNNotificationAttachment</code>!</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UNNotificationAttachment 设置图片 URL 到 Caches 目录,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/49029846/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/49029846/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UNNotificationAttachment 设置图片 URL 到 Caches 目录