jsonswiftnsdatansurl

Swift read json from file outside of Application bundle


I have spent at least 2 hours trying before posting this rather simple question. The following code works when the json file lives inside the the application bundle.

if let file = Bundle.main.url(forResource: "data", withExtension: "json") {....

I'm reading the json file this way...

let myData = try Data(contentsOf: file as URL)

I can't access an identical copy of the file from "/Library/Application Support/AppFolder/data.json".

The following doesn't work

let filepath = "/Library/Application Support/AppFolder/data.json"
if let file = NSURL(string: filepath) {...

Solution

  • Apart from the fact that URLs in the file system must always be created with NSURL(fileURLWithPath...) it's recommended to retrieve specific system folders with one the dedicated APIs:

    let applicationSupportFolderURL = try! NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory,
                                                                   inDomain: .LocalDomainMask,
                                                          appropriateForURL: nil,
                                                                     create: false)
    let jsonDataURL = applicationSupportFolderURL.URLByAppendingPathComponent("AppFolder/data.json")
    

    or in Swift 3 (which is pretty much shorter)

    let applicationSupportFolderURL = try! FileManager.default.url(for: .applicationSupportDirectory, 
                                                                    in: .localDomainMask, 
                                                        appropriateFor: nil, 
                                                                create: false)
    let jsonDataURL = applicationSupportFolderURL.appendingPathComponent("AppFolder/data.json")
    

    Or – in iOS 16+ and macOS 13+ – still more convenient

    let jsonDataURL = URL.applicationSupportDirectory.appending(path: "AppFolder/data.json")