nyitguy
nyitguy

Reputation: 608

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

Upvotes: 1

Views: 2225

Answers (2)

vadian
vadian

Reputation: 285069

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")

Upvotes: 2

Santosh
Santosh

Reputation: 2914

Try: NSURL.init(fileURLWithPath: "your_path")

string: produces an NSURL that represents the string as given. So the string like "http://www.google.com" and the URL represents http://www.google.com.

fileURLWithPath: takes a path, not a URL, and produces an NSURL that represents the path using a file:// URL. So if you give it /foo/bar/baz the URL would represent file:///foo/bar/baz.

Upvotes: 0

Related Questions