Swift - How do I get the file path inside a folder - ios

I have a set of audio files inside a folder. I am able to access the file when the file is placed at main bundle, but if the files are moved inside the folder I am not able to access the files.
Code:
let audioFileName:String = "audioFiles/" + String(index)
let audioFile = NSBundle.mainBundle().pathForResource(audioFileName, ofType: "mp3")!
I have an audio file inside the folder audioFiles and I would want to get its path.
Error:
fatal error: unexpectedly found nil while unwrapping an Optional value

First make sure when you drag your folder audioFiles to your project to check copy items if needed and select create folder references. Make sure it shows a blue folder if your project.
Also NSBundle method pathForResource has an initialiser that you can specify in which directory your files are located:
let audioFileName = "audioName"
if let audioFilePath = Bundle.main.path(forResource: audioFileName, ofType: "mp3", inDirectory: "audioFiles") {
print(audioFilePath)
}
If you would like to get that file URL you can use NSBundle method URLForResource(withExtension:, subdirectory:)
if let audioFileURL = Bundle.main.url(forResource: audioFileName, withExtension: "mp3", subdirectory: "audioFiles") {
print(audioFileURL)
}

The answer by Leo should work, the critical step is checking "Copy Items if Needed". However, what do you do if you already created a file or forgot that critical step?
Its easy to fix.
Go to Project -> Build Phases -> Copy Bundle Resources
Here you will see a handy list of all the files you've added to your bundle (including all your xcassets!)
Click the add button, and find your missing unlinked file.
Your code will now work (I built my own example, so it won't be same as yours in name):
if let url = Bundle.main.url(forResource: "testData2", withExtension: "txt") {
do {
let myData = try Data(contentsOf: url)
print(myData.count)
} catch {
print(error)
}
}
So why weren't we finding the file to begin with? Simple. We were asking the bundle. "Hey where is my file". Bundle was like... I don't know about that file, and if you checked the list of what was part of it (the Bundle Resources that are being copied) it wasn't there. taDa!

Related

can't access ios bundle resource

I am adding my first .wav file to my iOS project using XCode 11.3.1. I have tried various ways to access this resource:
let fileURL = Bundle.main.url(forResource: "greetings.wav", withExtension: nil)
let fileURL = Bundle.main.url(forResource: "greetings", withExtension: "wav")
let fileURL = Bundle.main.path(forResource: "greetings", ofType: "wav")
In all of these cases, fileURL is nil. Other things I have tried:
When I click on the .wav in Project Navigator, I see that Target Membership is checked for my target.
I have ensured greetings.wav is in the same folder as my ViewController which is executing the above statement.
I have also tried both the "Copy to Group" and "Copy to Folder Reference" when adding this resource
Nothing as of yet has produced a non-nil fileURL. Any help/additional troubleshooting so that I can get a valid URL for my .wav file would be greatly appreciated! Thanks.
Check whether your file is available in Copy Bundle Resources under build settings
Just offering possible suggestions here:
Check if you have imported the AVFoundation Module
Check if your resource is called "greetings.wav"

Beginner question: Reading a resource text file on MacOS using Swift

I'm new to this and apologize if it's basic. I have tried to research and I either get iOS posts, or old Xcode posts - none that are helping me with a basic need.
I want to have a bundled text file in my Swift/SwiftUI/MacOS app. It's just a text file, say sample.txt
I want to read it and do something with it.
I did the following:
Created a folder called "Resources" in my project
Added the text file - sample.txt
In my SwiftUI code, I did the following
if let filepath = Bundle.main.path(forResource: "sample", ofType: "txt") {
do {
print("...getting resource")
let contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
// contents could not be loaded
print(error)
}
} else {
print("no such file!")
}
And I get no such file
I changed the forResource: "sample" to forResource: "Resource/sample" and that didn't help either.
What should I be doing?
Thank you
It's not necessary to create an extra folder Resources. Just add the file to the project. It will be moved into the Resources folder of the app while being built.
And make sure that the Target Membership checkbox of the file is checked.

Where is the right place in the project to put a resource text file to read in an iOS App?

I'm trying to read a text file in a new App, but when it runs the file cannot be found.
I'm not sure where in the project I should put the file. I dragged it into the Assets folder from finder, but it's still not found. I looked at a similar question but the answer was in a much older version of Xcode and didn't solve my problem. I'm using Xcode 11.1
if let filepath = Bundle.main.path(forResource: "BibleTable", ofType: "csv") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
print("Error reading file BibleTable.csv")
}
} else {
print("File not found")
}
It gives "File not found"
Anywhere you fancy in the Bundle other than the assets folder, just as long as you your app (and any test target) is selected as a target in the File Inspector's Target Membership component.

Storing Sounds In a Folder (Swift File Path) [duplicate]

I have a set of audio files inside a folder. I am able to access the file when the file is placed at main bundle, but if the files are moved inside the folder I am not able to access the files.
Code:
let audioFileName:String = "audioFiles/" + String(index)
let audioFile = NSBundle.mainBundle().pathForResource(audioFileName, ofType: "mp3")!
I have an audio file inside the folder audioFiles and I would want to get its path.
Error:
fatal error: unexpectedly found nil while unwrapping an Optional value
First make sure when you drag your folder audioFiles to your project to check copy items if needed and select create folder references. Make sure it shows a blue folder if your project.
Also NSBundle method pathForResource has an initialiser that you can specify in which directory your files are located:
let audioFileName = "audioName"
if let audioFilePath = Bundle.main.path(forResource: audioFileName, ofType: "mp3", inDirectory: "audioFiles") {
print(audioFilePath)
}
If you would like to get that file URL you can use NSBundle method URLForResource(withExtension:, subdirectory:)
if let audioFileURL = Bundle.main.url(forResource: audioFileName, withExtension: "mp3", subdirectory: "audioFiles") {
print(audioFileURL)
}
The answer by Leo should work, the critical step is checking "Copy Items if Needed". However, what do you do if you already created a file or forgot that critical step?
Its easy to fix.
Go to Project -> Build Phases -> Copy Bundle Resources
Here you will see a handy list of all the files you've added to your bundle (including all your xcassets!)
Click the add button, and find your missing unlinked file.
Your code will now work (I built my own example, so it won't be same as yours in name):
if let url = Bundle.main.url(forResource: "testData2", withExtension: "txt") {
do {
let myData = try Data(contentsOf: url)
print(myData.count)
} catch {
print(error)
}
}
So why weren't we finding the file to begin with? Simple. We were asking the bundle. "Hey where is my file". Bundle was like... I don't know about that file, and if you checked the list of what was part of it (the Bundle Resources that are being copied) it wasn't there. taDa!

Cannot find my file

I have copied the file to the project and I am new to coding in swift, but I assumed that the file would deploy to my device with all the resource files in the project. this is my code which fails to find the file or copy from the bundle
if let dirs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .AllDomainsMask, true) as ? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file)
var checkValidation = NSFileManager.defaultManager()
if checkValidation.fileExistsAtPath(path) {
println("FILE AVAILABLE")
} else {
println("FILE NOT AVAILABLE")
// Copy the file from the Bundle and write it to the Device:
let pathToBundledDB = NSBundle.mainBundle().pathForResource("pcQuestionDBA", ofType: "txt")
var error: NSError ?
if NSFileManager.defaultManager().copyItemAtPath(pathToBundledDB!, toPath: dir, error: & error) {
}
I know I must be doing something fundamentally wrong and any advice would be truly appreciated - thanks
An Update:
I had copied the file into the project folder, however, I deleted the file and tried to copy it in anew, and I received an error stating that the file already existed in the folder. I think I had confused Xcode with the multiple moves and variations I tried in an attempt to fix my bug and find the file. I renamed the file and started from scratch and it all works well now. Thanks so much for your quick replies, it led me to the solution in the end - cheers
The problem there is that you should be passing a path to the file but you passed the path to the directory.
Try like this:
NSFileManager.defaultManager().copyItemAtPath(pathToBundledDB!, toPath: path, error: &error)

Resources