nyitguy nyitguy - 1 year ago 153
JSON Question

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) {...

Answer Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download