1

I am trying to read a file in my Bundle using the following code.

let bundle =  Bundle(for: type(of: self))
let path = bundle.url(forResource: "file1", withExtension: "xml")!

But path returns nil. I have try Bundle.main, but I get the same error. I have added the files in the bundle by

  1. drag my file to Xcode and clicks all the targets in the pop up dialog.
  2. select 'copy items if needed'
  3. clicks all the targets in the pop up dialog.

I tried to debug, but from the bundle object in the debugger, I can't find a property which shows me what resources it has or not.

Can you please tell me how to fix the issue?

Update: If I manually copy the files (in Macos Finder) to this directory

/Users/john/Library/Developer/Xcode/DerivedData/MyProject/Build/Products/Debug

Then, the swift code can find the file. Can you please tell me what do I need to do to add file to Main Bundle?

2
  • That's not how you get the path of a resource in the bundle.
    – El Tomato
    Commented Jul 23, 2020 at 3:43
  • Select the file in the project navigator, press ⌥⌘1 and check if the checkbox in Target Membership ist checked.
    – vadian
    Commented Jul 23, 2020 at 4:34

1 Answer 1

12
  1. Click the target of project.
  2. Select the item of Build Phase.
  3. under Copy Bundle Resources check if your file is listed or not. If not listed add with the plus button. enter image description here
1
  • Thanks. I did the step above. I see the files are copy in `/Users/hap497/Library/Developer/Xcode/DerivedData/MyProject/MyProjectTests.xctest/Contents/Resources. But the path is still nil when I look for it likes let bundle = Bundle(for: type(of: self)) var path = bundle.url(forResource: "file", withExtension: "json"). When I debug the code, i see teh bundle is pointing to MyProject/MyProjectTests.xctest. not Contents/Resources/
    – hap497
    Commented Jul 23, 2020 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.