Bundle.main.path(forResource:ofType:inDirectory:) returns nil
Solution 1
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.
Solution 2
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")
}
Solution 3
Click on your file on your navigation panel and open the Right Panel/ Property Inspector.
Ensure that you add to target membership
Solution 4
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!)
Solution 5
Swift 3.0
let fileNmae = "demo"
let path = Bundle.main.path(forResource: fileName, 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.
Related videos on Youtube
Zakarius Jay Poggenpohl
Updated on August 17, 2021Comments
-
Zakarius Jay Poggenpohl over 2 years
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 get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt") { do { let contents = try String(contentsOfFile: filepath) print(contents) } catch { print("Contents could not be loaded.") } } else { print("newTest.txt not found.") }
The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.
-
Himanshu Moradiya over 7 yearslet path : String = Bundle.main.path(forResource: "charlie", ofType: "txt")! let url : URL = URL(fileURLWithPath: path)
-
Leo Dabus over 7 yearsPossible duplicate of stackoverflow.com/questions/34548771/…
-
Zakarius Jay Poggenpohl over 7 years@LeoDabus my problem is similar to [link]stackoverflow.com/questions/40822170/… (which you also commented on) and also gives me the same error.
-
Himanshu Moradiya over 7 yearsBrother your problem solve or not ?
-
Zakarius Jay Poggenpohl over 7 yearsNo, same error. :.(...
-
Himanshu Moradiya over 7 yearsIN my code which line you got error mention in my answer so i can help you
-
Zakarius Jay Poggenpohl over 7 years"let content = try String(..." gives the same error. I dragged & dropped my file into the project at the same level as the main.swift and made sure the 'Create Folder References' and 'Add to targets:' were checked.
-
Himanshu Moradiya over 7 yearslet content = try String(contentsOfFile:path!, encoding: String.Encoding.utf8) use this line
-
Zakarius Jay Poggenpohl over 7 yearsThat's exactly what I did use and get the same error.
-
Himanshu Moradiya over 7 yearsare you using xcode 8.1 right ?
-
Zakarius Jay Poggenpohl over 7 yearsCurrently using: Xcode 8.2.1
-
Himanshu Moradiya over 7 years@ZakariusJayPoggenpohl just remove your code and use my code and see any error occure or not ?
-
Zakarius Jay Poggenpohl over 7 yearsI just tried... only changed the file name to "testFile" (instead of your code's "demo") and I got the original error.
-
Himanshu Moradiya over 7 yearsin my code i dont think so that kind of error you just clean your project and create again new .txt file and add in it again in your project and run my code .
-
-
Himanshu Moradiya over 7 years@LeoDabus wait i just convert this code in swift 3.0
-
Zakarius Jay Poggenpohl over 7 yearsI really appreciate your try to help, but I get the following error: fatal error: unexpectedly found nil while unwrapping an Optional value
-
Himanshu Moradiya over 7 yearswhich line ? @ZakariusJayPoggenpohl
-
Christopher Wade Cantley almost 7 yearsI added the file to "Copy Bundle Resources" however I also found it in my "Compile Sources" list which is because it was originally a swift file until I changed the extension. But changing the extension didn't remove it from "Compile Sources". So I pulled it out, ran it and worked like a charm.
-
Trev14 over 6 yearsThis worked for me when nothing else worked. Why would a file I drop into Xcode not automatically show up under "Copy Bundle Resources"???
-
mayankk2308 almost 6 yearsThank you. This helped me, as I was testing some code in the Playground (part of a larger project).
-
Micah Montoya over 5 yearsFor anyone else that see this and this is the solution for you as it was for me, you have to do this anytime the file gets replaced with a new version.
-
andrewcar over 5 years@Trev14 makes no sense that this doesn't happen automatically
-
jpcarreira almost 5 yearsInsane, lost a couple of hours on this when I forgot this "trick" on checking what's being added to the app bundle. The problem was I was using another IDE where I added the file and that IDE didn't edit the .pbxproj, thus I didn't have my resource in the app bundle
-
John Pitts almost 3 yearsDidn't work. Assets.xcassets was already there anyway. The only solution that works is to add the file to the list of project files, which is really messy. Essentially, you have to create your OWN assets folder-- totally annoying. Be sure to check "Create Groups" and "Add to Target" when you drag your file into the project.