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)")
}
Related
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.
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.
I have a few items that are saved to the documents directory. I currently need those to be moved programmatically to another directory. I created the new directory successfully, but it doesn't seem to be looking at that when using FileManager.default.moveItem.
Code used to created directory.
let path = getDocumentsDirectory().appendingPathComponent("Media").path
do{
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
print("\nDIRECTORY 'Media' CREATED")
}catch {
print("\nDIRECTORY 'Media' WAS NOT ABLE TO BE CREATED")
print("ERROR - \(error)")
}
I use this code to check my URL.
let mediaURL = getDocumentsDirectory().appendingPathComponent("Media")
print("\nMEDIA URL: \(mediaURL)")
Which outputs this.
MEDIA URL:file:///Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/Media/
Here is the code I'm using to move the items.
do{
try FileManager.default.moveItem(at: url, to: mediaURL)
print("\nFILE MOVED TO NEW MEDIA PATH SUCCESSFULLY")
}catch {
print("\nCOULDN'T MOVE FILE TO NEW MEDIA PATH")
print("ERROR - \(error)")
}
Here is the error I'm receiving for each item that I try to move.
COULDN'T MOVE FILE TO NEW MEDIA PATH
ERROR - Error Domain=NSCocoaErrorDomain Code=516 "“image_5” couldn’t be moved to “Documents” because an item with the same name already exists." UserInfo= {NSSourceFilePathErrorKey=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/image_5, NSUserStringVariant=(
Move
), NSDestinationFilePath=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/Media, NSFilePath=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/image_5, NSUnderlyingError=0x60000024fff0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
The media directory should be empty, as it is newly created, so the error I'm receiving is a bit confusing. It's also saying it's trying to move it to 'Documents', but it should be moving to 'Media'.What is causing this issue, and how can I resolve it? I'm just trying to move the items saved in 'Documents' to the new directory, 'Media'.
You must append the file name to the destination URL. Per the docs:
The new location for the item in srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file or directory in its new location. This parameter must not be nil.
Delete the old file if exist
let url = NSUrl(string: "...")
if NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
try! NSFileManager.defaultManager().removeItemAtURL(url)
}
Update:
Swift 5.1.2
let url = URL(string: mp3FilePath)
if FileManager.default.fileExists(atPath: url!.path) {
try! FileManager.default.removeItem(at: url!)
}
This worked for me - Add the name of file too in destination path
let nameFile = (songPath as NSString).lastPathComponent
let fileDest = destinationDirectoryPath + "/" + nameFile
//Now move the song files
try fileManager.moveItem(atPath: sourceFilePath, toPath: fileDest)
my problem is when i try to copy images from the photo library to the filesystem i get the error the error is
(Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0926.JPG”
couldn’t be opened because you don’t have permission to view it."
UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0926.JPG,
NSUnderlyingError=0x15649630 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}})
my code is :
let fileManager = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let document = fileManager[0]
var i = 0
for asset in arrayOfAssets {
let filePath = document.appendingPathComponent("image\(arrayOfAssets.count + i).png")
i += 1
PHImageManager.default().requestImageData(for: asset, options: nil) { (data, nil, _ , info) in
let url = info?["PHImageFileURLKey"] as! NSURL
do {
try FileManager.default.copyItem(at: url as URL, to: filePath)
}catch {
print(error)
}
// print(filePath)
}
}
please if anyone can help me
thanks all
It sounds like you're trying to open a file located here : NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0926.JPG
By default access to this directory is not permitted, you can only access files located in the document directory, for security reasons.
I don't find where this URL comes from in your code, but according to the NSError you are trying to access an image outside the permitted area of the file system.
Please check the permission option in plist for Photos Library in iOS 11.
Also you can save data in TEMP directory and fetch it when needed and after use
clean data in TEMP directory.
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