简体   繁体   中英

How to read data from a file in the App's bundle I macOS?

I'm trying to read the data from a txt file on macOS. I use String(contentsOf:) and Bundle.main.path(forResource:) like I would on iOS. However, this doesn't work on macOS. I have tried several solutions from other posts but because of macOS they don't seem to work.

Thanks in advance.

Edit: My code:

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)

I can save the data to a folder on disk, but I want to ship this file with my app.

URL(string is the wrong API. It's only for URL strings starting with a scheme ( http:// , file:// )

For file system paths you have to use URL(fileURLWithPath .

But in this situation there is a much better way

Replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM