Swift 从应用程序包外部的文件中读取 json
Swift read json from file outside of Application bundle
在发布这个相当简单的问题之前,我已经尝试了至少 2 个小时。当 json 文件位于应用程序包内时,以下代码有效。
if let file = Bundle.main.url(forResource: "data", withExtension: "json") {....
我正在以这种方式阅读 json 文件...
let myData = try Data(contentsOf: file as URL)
我无法从“/Library/Application Support/AppFolder/data.json”访问文件的相同副本。
以下无效
let filepath = "/Library/Application Support/AppFolder/data.json"
if let file = NSURL(string: filepath) {...
尝试:NSURL.init(fileURLWithPath: "your_path")
string:
生成表示给定字符串的 NSURL。所以像“http://www.google.com" and the URL represents http://www.google.com.
这样的字符串
fileURLWithPath:
采用路径,而不是 URL,并使用 file:// URL 生成表示路径的 NSURL。因此,如果您给它 /foo/bar/baz
,则 URL 将代表 file:///foo/bar/baz
。
除了文件系统中的 URL 必须始终使用 NSURL(fileURLWithPath...)
创建之外,建议使用一个专用 API 检索特定系统文件夹:
let applicationSupportFolderURL = try! NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory,
inDomain: .LocalDomainMask,
appropriateForURL: nil,
create: false)
let jsonDataURL = applicationSupportFolderURL.URLByAppendingPathComponent("AppFolder/data.json")
或 Swift 3(短得多)
let applicationSupportFolderURL = try! FileManager.default.url(for: .applicationSupportDirectory,
in: .localDomainMask,
appropriateFor: nil,
create: false)
let jsonDataURL = applicationSupportFolderURL.appendingPathComponent("AppFolder/data.json")
在发布这个相当简单的问题之前,我已经尝试了至少 2 个小时。当 json 文件位于应用程序包内时,以下代码有效。
if let file = Bundle.main.url(forResource: "data", withExtension: "json") {....
我正在以这种方式阅读 json 文件...
let myData = try Data(contentsOf: file as URL)
我无法从“/Library/Application Support/AppFolder/data.json”访问文件的相同副本。
以下无效
let filepath = "/Library/Application Support/AppFolder/data.json"
if let file = NSURL(string: filepath) {...
尝试:NSURL.init(fileURLWithPath: "your_path")
string:
生成表示给定字符串的 NSURL。所以像“http://www.google.com" and the URL represents http://www.google.com.
fileURLWithPath:
采用路径,而不是 URL,并使用 file:// URL 生成表示路径的 NSURL。因此,如果您给它 /foo/bar/baz
,则 URL 将代表 file:///foo/bar/baz
。
除了文件系统中的 URL 必须始终使用 NSURL(fileURLWithPath...)
创建之外,建议使用一个专用 API 检索特定系统文件夹:
let applicationSupportFolderURL = try! NSFileManager.defaultManager().URLForDirectory(.ApplicationSupportDirectory,
inDomain: .LocalDomainMask,
appropriateForURL: nil,
create: false)
let jsonDataURL = applicationSupportFolderURL.URLByAppendingPathComponent("AppFolder/data.json")
或 Swift 3(短得多)
let applicationSupportFolderURL = try! FileManager.default.url(for: .applicationSupportDirectory,
in: .localDomainMask,
appropriateFor: nil,
create: false)
let jsonDataURL = applicationSupportFolderURL.appendingPathComponent("AppFolder/data.json")