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)
Related
I'm trying to create a log.txt file inside a folder of a device, but I get this error:
NSCocoaErrorDomain Code=512 "The file “log.txt” couldn’t be saved in
the folder “Logs”.
The folder Logs already exists on the device, but I still get this error. Please find my code below:
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let logPath = path.appendingPathComponent("Logs").appendingPathComponent("log.txt")
try! "Hello world".write(to: logPath, atomically: true, encoding: .utf8)
However, if I replace the logPath with path.appendingPathComponent("log.txt"), it will work, BUT it creates the file outside of the folder Logs instead of inside.
How can I solve this?
I have fixed this problem by using the new function called appending(component:_) of the FileManager API.
The old one that I used in my question was not deprecated, but it did not work, and I still have no idea.
However, using the new one above makes everything works just fine.
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.
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.
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!
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!