Bundle.main.path(forResource:ofType:inDirectory:) returns nil

后端 未结 10 2410
遥遥无期
遥遥无期 2020-12-07 13:08

Try not to laugh or cry -- I\'m just getting back into coding after 20 years out...

I\'ve spent more than 4 hours looking at references and trying code snippets to g

相关标签:
10条回答
  • 2020-12-07 13:34

    Ah, so just found myself dealing with the exact same problem as the OP.

    The problem is that the solutions given here and here do not work when the code is being executed in a playground, since the Options menu of add files looks different for it does not show the Add to targets field:

    When inside a .playground file, instead press the Hide or show the Navigator button on the top-right of your Xcode window (visual impression)-->

    Then, once the Navigator folds open on the left-side of the Xcode window, simply drag & drop your file to the Resources directory of your playground.

    If your setup looks anything like the following you should be ok:

    0 讨论(0)
  • 2020-12-07 13:36

    I think you don't want the inDirectory: method. Try this instead:

    if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt") {
    
    0 讨论(0)
  • 2020-12-07 13:42

    It's crazy how much time such a simple problem can cost.

    Some answers here helped me but I always tried:

    Bundle.main.url(forResource: selectedTitle, withExtension: "mp3")
    

    For some reason that doesn't work, but getting the path and translating it to a URL afterwards works:

    let path = Bundle.main.path(forResource: selectedTitle, ofType: "mp3")
    let url = URL(fileURLWithPath: path!)
    
    0 讨论(0)
  • 2020-12-07 13:43

    This was helpful for me: xcode - copy a folder structure into my app bundle

    Mark "create folder references" option when you create assets in nested folders.

    Then find path to the file like this:

    let path = Bundle(for: type(of : self)).path(forResource: "some_folder_a/some_folder_b/response.json", ofType: nil)
    
    0 讨论(0)
  • 2020-12-07 13:46

    Double check the Options in the add files menu when adding the file. The target in Add to targets must be ticked to add it to the bundle:

    In case you are actually in another bundle (test for instance), use:

    guard let fileURL = Bundle(for: type(of: self)).url(forResource: fileName withExtension:"txt") else {
            fatalError("File not found")
    }
    
    0 讨论(0)
  • 2020-12-07 13:46

    I added file.txt to my project and it was automatically added to the Copy Bundle Files of my project. For me, I had to remove the extension from the forResource and it worked.

    let path = Bundle.main.path(forResource: "file", ofType: "txt") // not forResource: "file.txt"
    
    0 讨论(0)
提交回复
热议问题