0

I have a json file stored in the FileManager of my app and I want to access and decode it for my widget. I use the following url for the file:

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

where filename is "list".

However I don't think the target can access the file in my app's FileManager as I get the error 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."

There might be some extra details you can use from my previous question

Arnav Motwani
  • 707
  • 7
  • 26

1 Answers1

1

If you want to share files between your widget and your app, rather than using the typical .documentDirectory, you can use an "App Group" instead.

You'll need to add the "App Groups" entitlement (https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups) and then you can access a shared container url (https://developer.apple.com/documentation/foundation/filemanager/1412643-containerurl)

Your container URL will then be accessible by doing something like FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "APP_GROUP_ID_HERE") which will return a URL?

You can append components to that URL just as you were doing in your original code.

Additional reading: https://useyourloaf.com/blog/sharing-data-with-a-widget/

jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Just to be clear, as my app has been out for a couple months now, I would also need to transfer the app files onto this new path so that the app and the widget stay in sync. As in I will have to add some code to move the file from the documentDirectory to the shared container? – Arnav Motwani May 05 '21 at 16:03
  • 1
    Yes, unfortunately, you would – jnpdx May 05 '21 at 16:04
  • 1
    If this answered your question, you can mark it as accepted with the green checkmark. – jnpdx May 06 '21 at 22:18