I am trying to load an existing text file that is stored as a resource that is bundled inside my Xcode project. I am unable to set a variable to the path to this file and therefore cannot get to the read stage.
I create a project: new->MacOS->Command Line Tool->called “Pants”
In the Project Navigator, click on the yellow folder called Pants. File->New file…MacOS->Resource->Rich Text File. I name this “Nick”. Group is Pants, Targets is ticked as Pants.
I type “Hello wonderful world” into this file. File->Close “Nick.rtf”
In Project Navigator, under yellow folder Pants, I can see Nick.rtf
In Project Navigator, click top level blue icon, Pants. Select Build Phases->+, New Copy Bundle Resource Phase. I drag the Nick.rtf file from the Project Navigator into the “Add resource files here”. [I've noticed that sometimes the file has already been put here]
In main.swift, I add my code given below. This is modified from: Read and write a String from text file
import Foundation print("Hello, World!") if let path = Bundle.main.path(forResource:"Nick" , ofType: nil) { print("will read") } else { print("Failed to load file from bundle") }
When this is run, Product->Run, my file is not found:
Hello, World! Failed to load file from bundle Program ended with exit code: 0
a. I have tried changing Type “rtf”. I have tried Nil. If use the full project path in Mac Finder, I can see the file “Nick.rtf” stored in Documents->SwiftCode->Pants->Pants
b. I have tried variations of names, file types, locations, etc. I have tried Files->Add files to “Pants”…
c. If I drag the Nick.rtf from the Project Navigator into my source file, it gives the path as:
/Users/XXX/Documents/SwiftCode/Pants/Pants/Nick.rtf
I still appear unable to determine the path of my resource in the bundle inside my project using Swift code, so that I can then (finally) load the text file. I assume the file is not actually inside the resource bundle - I cannot determine how to get it there?