0

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.

  1. I create a project: new->MacOS->Command Line Tool->called “Pants”

  2. 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.

  3. I type “Hello wonderful world” into this file. File->Close “Nick.rtf”

  4. In Project Navigator, under yellow folder Pants, I can see Nick.rtf

  5. 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]

  6. 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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Nick RT
  • 21
  • 2
  • The problem is that "Command-line Tool" targets don't really have a bundle. – jscs Feb 04 '18 at 16:13
  • Also [Getting path for resource in command line tool](https://stackoverflow.com/q/38422467) – jscs Feb 04 '18 at 16:13
  • Thank you for all your help. I should have realised that the Command-Line tool does not have a bundle. Rather obvious now you say it! It is a shame that the IDE does not help you a little more - ah well, back to my days of 8-bit opcodes... – Nick RT Feb 14 '18 at 17:10

0 Answers0