如何从Mac OS的应用程序捆绑包中的文件读取数据?

时间:2018-10-25 19:38:52

标签: swift macos file cocoa

我正在尝试从macOS上的txt文件读取数据。我像在iOS上一样使用String(contentsOf :)和Bundle.main.path(forResource :)。但是,这在macOS上不起作用。我从其他帖子中尝试了几种解决方案,但由于macOS,它们似乎无法正常工作。

谢谢。

编辑: 我的代码:

let path = Bundle.main.path(forResource: "file", ofType: "txt")! // no error
let url = URL(string: path)! // no error
let contents: String
do {
     contents = try String(contentsOf: url)
} catch {
    print(error) // Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported."
    contents = "ERROR"
}
print(contents)

我可以将数据保存到磁盘上的文件夹中,但是我想将此文件与我的应用一起发送。

1 个答案:

答案 0 :(得分:0)

URL(string是错误的API。仅适用于以方案(http://file://)开头的URL字符串

对于文件系统路径,您必须使用URL(fileURLWithPath

但是在这种情况下,有更好的方法

替换

let path = Bundle.main.path(forResource: "file", ofType: "txt")!
let url = URL(string: path)! // no error

使用

let url = Bundle.main.url(forResource: "file", withExtension: "txt")