NSFileManager fileExistsAtPath unable to overwrite existing file in Swift 2 - ios

Hello I'm upgrading my existing code to Swift 2, and I need some help with the copy of a file inside the DocumentDirectoy.
This is converted code I'm using to check if the file exists, and if it does, we should copy it either way, but it keeps returning an error saying the file exists, which it is true, but we need to overwrite it.
func copyXMLFile()
{
// Get a reference for the Document directory
let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
// Get a reference for the data.xml file
xmlPathInDocument = rootPath.stringByAppendingString("data.xml")
if NSFileManager.defaultManager().fileExistsAtPath(xmlPathInDocument){
print("xml file exists")
let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
do {
// copy file from main bundle to documents directory
print("copy")
try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
} catch let error as NSError {
// Catch fires here, with an NSErrro being thrown
print("error occurred, here are the details:\n \(error)")
}
}
else
{
// copy the file either way
let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
do {
// copy file from main bundle to documents directory
print("copy")
try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
} catch let error as NSError {
// Catch fires here, with an NSErrro being thrown
print("error occurred, here are the details:\n \(error)")
}
}
}
error occurred, here are the details:
Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be
completed. (Cocoa error 516.)" UserInfo=0x7a67b680
{NSSourceFilePathErrorKey=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Bundle/Application/E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE/myApp.app/data.xml,
NSUserStringVariant=(
Copy ), NSFilePath=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Bundle/Application/E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE/myApp.app/data.xml,
NSDestinationFilePath=/Users/User1/Library/Developer/CoreSimulator/Devices/0E591E5B-2E2F-4CCB-9099-95CE1EA3F557/data/Containers/Data/Application/09F690B3-BDD8-4482-ADDE-E33F30D4B873/Documentsdata.xml,
NSUnderlyingError=0x7a67dd80 "The operation couldn’t be completed.
File exists"}
Please HELP!

Implement NSFileManagerDelegate and the delegate method
optional func fileManager(_ fileManager: NSFileManager,
shouldProceedAfterError error: NSError,
copyingItemAtURL srcURL: NSURL,
toURL dstURL: NSURL) -> Bool
and return true
Alternatively you could use
func replaceItemAtURL(_ originalItemURL: NSURL,
withItemAtURL newItemURL: NSURL,
backupItemName backupItemName: String?,
options options: NSFileManagerItemReplacementOptions,
resultingItemURL resultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws

Related

FileManager "File exists" when copying files [duplicate]

This question already has answers here:
how to use writeToFile to save image in document directory?
(8 answers)
Closed 3 years ago.
I am trying to copy a file (audioFile) to DestinationURl however when I do I get this error:
Unable to create directory Error Domain=NSCocoaErrorDomain Code=516 "“20200116183746+0000.m4a” couldn’t be copied to “Documents” because an item with the same name already exists." UserInfo={NSSourceFilePathErrorKey=/<app>/Documents/20200116183746+0000.m4a, NSUserStringVariant=(
Copy
), NSDestinationFilePath=<appURL>/Documents/20200116183746+0000.m4a, NSUnderlyingError=0x600003c2d290 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
Here I my code
let DirPath = DocumentDirectory.appendingPathComponent(self.txtName.text ?? "NA")
do
{
try FileManager.default.createDirectory(atPath: DirPath!.path, withIntermediateDirectories: true, attributes: nil)
print("\n\n\nAudio file: \(self.audioFile)\n\n\n")
let desitationURl = ("\(DirPath!.path)/")
try FileManager.default.copyItem(atPath: self.audioFile.path, toPath: desitationURl)
}
catch let error as NSError
{
print("Unable to create directory \(error.debugDescription)")
}
I have removed the / on let desitationURl = ("(DirPath!.path)/") and I can see that the file has been generated and the folder is generated however nothing is moved.
Any help will be appreciated
Osian
You need to specify the actual name of the destination file, not just the directory it will go inside. The file manager is literally trying to save your file as the directory name. I cleaned your code up a bit to make it more readable, as well:
guard let dirURL = DocumentDirectory
.appendingPathComponent(self.txtName.text ?? "NA") else { return }
if !FileManager.default.fileExists(atPath: dirURL.path) {
do {
try FileManager.default
.createDirectory(atPath: dirURL.path,
withIntermediateDirectories: true,
attributes: nil)
} catch let error as NSError {
print("Unable to create directory \(error.debugDescription)")
}
}
print("\n\n\nAudio file: \(audioFile)\n\n\n")
let dstURL = dirURL.appendingPathComponent(audioFile.lastPathComponent)
do {
try FileManager.default.copyItem(atPath: audioFile.path, toPath: dstURL.path)
} catch let error as NSError {
print("Unable to copy file \(error.debugDescription)")
}

Cannot write to local storage "No such file or directory" issue in iOS swift [duplicate]

This question already has answers here:
NSFileManager.defaultManager().fileExistsAtPath returns false instead of true
(2 answers)
Closed 3 years ago.
Trying to save an image as below to local storage.
if let imageData: Data = UIImagePNGRepresentation(self.emitterImageView.image!) {
try! imageData.write(to: savedImagePath, options: [])
}
But crashes due to following error.
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error:
Error Domain=NSCocoaErrorDomain Code=4 "The file
“PHDEmitterImage1.png” doesn’t exist."
UserInfo={NSFilePath=/private/var/mobile/Containers/Data/Application/41D876EC-7D65-4AB1-820E-EDE46FAE8675/tmp/PHDEmitterBackup/PHDEmitterImage1.png,
NSUnderlyingError=0x15bf21790 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}
Where is the issue?
saved image path is file:/private/var/mobile/Containers/Data/Application/41D876EC-7D65-4AB1-820E-EDE46FAE8675/tmp/PHDEmitterBackup/PHDEmitterImage1.png
Custom path
func emitterBackupDirectoryPath() -> String? {
let dataPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.absoluteString
//let dataPath = URL(fileURLWithPath: documentsDir).appendingPathComponent("/PHDEmitterBackup").absoluteString
//let dataPath = documentsDir?.appendingPathComponent("/PHDEmitterBackup").absoluteString
if !FileManager.default.fileExists(atPath: dataPath!) { //if does not exist
do {
try FileManager.default.createDirectory(atPath: dataPath!, withIntermediateDirectories: false, attributes: nil) //Create folder
} catch {
}
}
return dataPath
}
Solve the issue helping above comments and I state it here because it may help to someone. The problem is with the dataPath variable is a URL. To get the path as a String, need to use the path property, not absoluteString.

Writing file to iCloud drive Error Domain=NSCocoaErrorDomain Code=256

I am trying to send a file from local storage of sandboxed app to icloud drive.
Unfortunately I am getting this error:
Error Domain=NSCocoaErrorDomain Code=256 "Soubor „About.txt" couldn't open." UserInfo={NSURL=file:///var/mobile/Containers/Data/Application/1626D575-64CF-4B61-B6B1-38F0B76ED135/Documents/path/path/About.txt, NSUserStringVariant=(
"Cannot disable syncing on a unsynced item."
), NSUnderlyingError=0x13d819630 {Error Domain=NSPOSIXErrorDomain Code=37 "Operation already in progress"}}
My code is as follows:
struct DocumentsDirectory {
static let localDocumentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
static let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
}
Copying function:
func copyFileFromLocacPathToIcloud (fileName:String, filePath:URL, folderName:String) {
let fileManager = FileManager.default
if (ICloudUtils.isiCloudEnabled(icloudURL: DocumentsDirectory.iCloudDocumentsURL)) {
let fileUrl = DocumentsDirectory.localDocumentsURL!.appendingPathComponent("path", isDirectory: true).appendingPathComponent("path", isDirectory:true).appendingPathComponent("About.txt")
if fileUrl.startAccessingSecurityScopedResource() {
}
Log.dbg(msg: "file exists at location \(fileManager.fileExists(atPath: fileUrl.path)) \(fileUrl)")
let iCLoudURL = DocumentsDirectory.iCloudDocumentsURL?.appendingPathComponent(fileName)
do {
try fileManager.setUbiquitous(false, itemAt: fileUrl, destinationURL: iCLoudURL!)
}catch {
Log.error(msg: "icloud save file \(error)")
fileUrl.stopAccessingSecurityScopedResource()
}
}
}
capabilities I have iCloud on. Somebody can help me with this issue ?
I know this question is old but shows up in google search so it may help others.
According to this doc when you try to send the file to iCloud you should set the flag to true. you where using false which is to remove the file from iCloud. Basically change the line from:
try fileManager.setUbiquitous(false, itemAt: fileUrl, destinationURL: iCLoudURL!)
to:
try fileManager.setUbiquitous(true, itemAt: fileUrl, destinationURL: iCLoudURL!)
Hope that helps.

Firebase Storage download to local file error

I'm trying to download the image f5bd8360.jpeg from my Firebase Storage.When I download this image to memory using dataWithMaxSize:completion, I'm able to download it.
My problem comes when I try to download the image to a local file using the writeToFile: instance method. I'm getting the following error:
Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown
error occurred, please check the server response."
UserInfo={object=images/f5bd8360.jpeg,
bucket=fir-test-3d9a6.appspot.com, NSLocalizedDescription=An unknown
error occurred, please check the server response.,
ResponseErrorDomain=NSCocoaErrorDomain, NSFilePath=/Documents/images,
NSUnderlyingError=0x1700562c0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}, ResponseErrorCode=513}"
Here is a snippet of my Swift code:
#IBAction func buttonClicked(_ sender: UIButton) {
// Get a reference to the storage service, using the default Firebase App
let storage = FIRStorage.storage()
// Get reference to the image on Firebase Storage
let imageRef = storage.reference(forURL: "gs://fir-test-3d9a6.appspot.com/images/f5bd8360.jpeg")
// Create local filesystem URL
let localURL: URL! = URL(string: "file:///Documents/images/f5bd8360.jpeg")
// Download to the local filesystem
let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
if (error != nil) {
print("Uh-oh, an error occurred!")
print(error)
} else {
print("Local file URL is returned")
}
}
}
I found another question with the same error I'm getting but it was never answered in full. I think the proposal is right. I don't have permissions to write in the file. However, I don't know how gain permissions. Any ideas?
The problem is that at the moment when you write this line:
let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
etc.
you don't yet have permission to write to that (localURL) location. To get the permission you need to write the following code before trying to write anything to localURL
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localURL = documentsURL.appendingPathComponent("filename")
By doing it you will write the file into the following path on your device (if you are testing on the real device):
file:///var/mobile/Containers/Data/Application/XXXXXXXetc.etc./Documents/filename
If you are testing on the simulator, the path will obviously be somewhere on the computer.

iOS Dropbox error loading thumbnails

I wanna get thumbnails for dropbox files that I display on a view. I know that I've to use the loadThumbnail method, but I don't get exactly how to do it.
I wrote this :
for file in dropboxMetadata.contents {
dbRestClient.loadThumbnail(file.path, ofSize: "s", intoPath: "https://api-content.dropbox.com/1/thumbnails/auto/")
}
but I get some errors like this :
error making request to /1/thumbnails/dropbox/star.jpg - (4) Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed.
Thanks for your help !
Petesh has the right idea. intoPath is the destination directory for those thumbnails.
Try this:
func createTempDirectory() -> String? {
let tempDirectoryTemplate = NSTemporaryDirectory().stringByAppendingPathComponent("XXXXX")
let fileManager = NSFileManager.defaultManager()
var err: NSErrorPointer = nil
// remove any previous temporary folder that's there, in case it's there
fileManager.removeItemAtPath(tempDirectoryTemplate)
if fileManager.createDirectoryAtPath(tempDirectoryTemplate, withIntermediateDirectories: true, attributes: nil, error: err) {
return tempDirectoryTemplate
} else {
print("can't create temporary directory at \(tempDirectoryTemplate)")
return nil
}
}
The above code for which I found in this question
Then you could change your own code to do something like:
let temporaryDirectory = createTempDirectory()
for file in dropboxMetadata.contents {
dbRestClient.loadThumbnail(file.path, ofSize: "s", intoPath: temporaryDirectory)
}
If this works, then you could change the "intoPath" parameter into any directory you think is more appropriate.

Resources