首页 > 解决方案 > 将 FileManager 或 App 目标中的文件共享到 WidgetExtension 目标

问题描述

我有一个 json 文件存储在我的应用程序的 FileManager 中,我想为我的小部件访问和解码它。我对文件使用以下网址:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        
let jsonURL = documentDirectory
    .appendingPathComponent(filename)
    .appendingPathExtension("json")

其中文件名是“列表”。

但是,当我收到错误消息时,我认为目标无法访问我的应用程序 FileManager 中的文件Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=260 "The file “list.json” couldn’t be opened because there is no such file."

您可以从我之前的问题中使用一些额外的细节

标签: jsonswiftswiftuiwidgetkit

解决方案


如果你想在你的小部件和你的应用程序之间共享文件,而不是使用典型的.documentDirectory,你可以使用“应用程序组”来代替。

您需要添加“应用程序组”权利 ( https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups ),然后您可以访问共享容器 url ( https://developer.apple .com/documentation/foundation/filemanager/1412643-containerurl )

然后,您的容器 URL 将可以通过执行类似FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "APP_GROUP_ID_HERE")返回的操作来访问URL?

URL您可以像在原始代码中那样添加组件。

补充阅读:https ://useyourloaf.com/blog/sharing-data-with-a-widget/


推荐阅读