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

后端 未结 10 2401
遥遥无期
遥遥无期 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:51

    Click on your file on your navigation panel and open the Right Panel/ Property Inspector.

    Ensure that you add to target membership

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

    Same problem, slightly different situation & solution. I'm following a tutorial that said to use the following code:

        // Start the background music:
        if let musicPath = Bundle.main.path(forResource:
            "Sound/BackgroundMusic.m4a", ofType: nil) {
            print("SHOULD HEAR MUSIC NOW")
            let url = URL(fileURLWithPath: musicPath)
    
            do {
                musicPlayer = try AVAudioPlayer(contentsOf: url)
                musicPlayer.numberOfLoops = -1
                musicPlayer.prepareToPlay()
                musicPlayer.play()
            }
            catch { print("Couldn't load music file") }
        }
    }
    

    I had the same issue as others but none of the solutions fixed the issue. After experimenting, all I did was remove Sound from the path in the following call and everything worked:

    Bundle.main.path(forResource: "BackgroundMusic.m4a", ofType: nil)
    

    It would seem that the tutorial was in error by telling me to include Sound in the path.

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

    Swift 3.0

    let fileNmae = "demo"
    
    let path = Bundle.main.path(forResource: fileNmae, ofType: "txt")
        do {
            let content = try String(contentsOfFile:path!, encoding: String.Encoding.utf8)
            print(content)
        } catch {
            print("nil")
        }
    

    SWift 2.0

    do{
          if let path = NSBundle.mainBundle().pathForResource("YOURTXTFILENAME", ofType: "txt"){
                 let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
                 let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
                  print(myStrings)
           }
      } catch let err as NSError {
                //do sth with Error
                print(err)
      }
    

    Output :

    Hello Hems
    Good Morning
    I m here for you dude.
    Happy Coding.
    
    0 讨论(0)
  • 2020-12-07 13:57

    The issue is that the file isn't being copied to your app bundle. To fix it:

    • Click your project
    • Click your target
    • Select Build Phases
    • Expand Copy Bundle Resources
    • Click '+' and select your file.
    0 讨论(0)
提交回复
热议问题