I am trying to copy a file from my bundle to the documents directory in iOS with the following code.
let bundlePath = NSBundle.mainBundle().pathForResource("information", ofType: ".png")
print(bundlePath, "\n") //prints the correct path
let destPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let fileManager = NSFileManager.defaultManager()
let fullDestPath = NSURL(fileURLWithPath: destPath).URLByAppendingPathComponent("information.png")
let fullDestPathString = String(fullDestPath)
print(fileManager.fileExistsAtPath(bundlePath!)) // prints true
do{
try fileManager.copyItemAtPath(bundlePath!, toPath: fullDestPathString)
}catch{
print("\n")
print(error)
}
Error Domain=NSCocoaErrorDomain Code=4 "The file “information.png” doesn’t exist." UserInfo={NSSourceFilePathErrorKey=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts.app/information.png, NSUserStringVariant=( Copy ), NSDestinationFilePath=file:///Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Data/Application/86A1BDD5-FAF2-486E-85A9-CF72A547C6CD/Documents/information.png, NSFilePath=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts.app/information.png, NSUnderlyingError=0x7fb53251cd80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
According to the fileManager.fileExistsAtPath()
the file does indeed exist. What am I doing wrong?
Misleading in some answers:
print(fileManager.fileExists(atPath: bundlePath!))
hence proposing this extension
version:
extension FileManager {
func copyfileToUserDocumentDirectory(forResource name: String,
ofType ext: String) throws
{
if let bundlePath = Bundle.main.path(forResource: name, ofType: ext),
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true).first {
let fileName = "\(name).\(ext)"
let fullDestPath = URL(fileURLWithPath: destPath)
.appendingPathComponent(fileName)
let fullDestPathString = fullDestPath.path
if !self.fileExists(atPath: fullDestPathString) {
try self.copyItem(atPath: bundlePath, toPath: fullDestPathString)
}
}
}
}
Usage
try fileManager.copyfileToUserDocumentDirectory(forResource: "information",
ofType: "png")
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With