NSBundle.mainBundle().URLForResource(“bach1”, withExtension: “jpg”) returning null

后端 未结 5 620
执笔经年
执笔经年 2021-01-02 10:28
NSBundle.mainBundle().URLForResource(\"bach1\", withExtension: \"jpg\")

The above code is returning null.

In order to check if the file exi

相关标签:
5条回答
  • 2021-01-02 10:42

    I found that you have to actually go into Build Phases -> Copy Bundle Resources and manually add your item sometimes to the bundle. In my case it was a video file that didn't get added to the bundle correctly on its own.

    0 讨论(0)
  • 2021-01-02 10:49

    Your problem is that NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") returns an optional NSURL. You need to use if let to unwrap it and extract your file path from the returned url as follow:

    if let resourceUrl = NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") {
        if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
            print("file found")
        }
    }
    
    0 讨论(0)
  • 2021-01-02 10:49

    NSBundle.URLForResource only returns files that are bundled in your application at build/compile time, like when you drag a file into your Xcode project and add it to your app target. You can typically use this when your app comes preloaded with resources you need, like images, movies, databases, and other files.

    It seems like savepath is a path your application wrote to while running (maybe into your app's Documents directory?). Because of this, the file is outside of the bundle and you will need to store that path/URL somewhere (or build it up again) if you need to reference the file in the future.

    0 讨论(0)
  • 2021-01-02 10:51

    Swift 3.x

    if let resourceUrl = Bundle.main.url(forResource: "bach1", withExtension: "jpg") {
        if FileManager.default.fileExists(atPath: resourceUrl.path) {
            print("file found")
        }
    }
    
    0 讨论(0)
  • 2021-01-02 10:53

    I had this issue too. My fix was:

    • Selecting the file in project navigator
    • Open the 'File Inspector' (on the right hand side pane)
    • Checking the app target in the Target Membership
    0 讨论(0)
提交回复
热议问题