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

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.

Related

How can I gzip a folder in Swift?

I have a set of files of different types(i.e. .m4a, .mov, .csv) which are saved inside a folder named Test. Now, I want to gzip the folder & send it to server (in order to avoid multiple API calls).
I tried the following (Using GzipSwift Framework) :
do {
let data = try Data(contentsOf: getFolderUrl())
let zippedData = try data.gzipped()
try zippedData.write(to: destinationUrl)
} catch {
print("Error: \(error)")
}
func getFolderUrl() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("Test")
return dataPath
}
This gives the following error on first line:
Error Domain=NSCocoaErrorDomain Code=257 "The file “Test” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/Xx...xX/Documents/Test, NSUnderlyingError=0x283151500 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}

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)")
}

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.

i have an issue on the file System on the actual device

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.

Reading from ApplicationSupportDirectory in iOS

Using LXLogger I am able to write log entries to file on the device and simulator (in addition to xcode console etc).
The default location which LXLogger stores the file is under the ApplicationSupportDirectory.
LXLogger writes to the file OK, and I can see the file is on my device (or on my mac HDD when using the simulator), but when I try to open the file I am told that the file does not exist.
I have added the error logs generated in line with the code.
I've tried a dozen different methods and multiple questions on here, to no avail.
let directory = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent(NSBundle.mainBundle().bundleIdentifier!, isDirectory: true).URLByAppendingPathComponent("logs", isDirectory: true)
do {
let array = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options:[])
var str = array[0].description
str = str.stringByReplacingOccurrencesOfString("file://", withString: "", options: .LiteralSearch, range: nil)
let fileURL = NSURL(fileURLWithPath:str)
log.info("fileURL contains: " + fileURL.absoluteString)
do {
log.info("Attempting to get contentsOfURL")
let data = try NSString(contentsOfFile: array[0].description,
encoding: NSASCIIStringEncoding)
logTextView.text = data as String
} catch let error as NSError {
log.error(error.description)
}
}
catch let error as NSError {
log.error(error.description)
}
Log Outputs from above code:
> 2016-03-31 21:43:52.121 [INFO] fileURL contains: file:///private/var/mobile/Containers/Data/Application/2F812C06-E204-4543-905C-F884C35DA198/Library/Application%2520Support/myname.myapp/logs/1_log.txt
> 2016-03-31 21:43:52.122 [INFO] Attempting to get contentsOfURL
> 2016-03-31 21:43:52.123 [ERROR] Error Domain=NSCocoaErrorDomain Code=260 "The file “1_log.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=file:///private/var/mobile/Containers/Data/Application/2F812C06-E204-4543-905C-F884C35DA198/Library/Application%20Support/myname.myapp/logs/1_log.txt, NSUnderlyingError=0x1376e0e00 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
So the code shows that the file is there (and i can physically open the copy on my mac), but the app can't find it.
Presumably its something to do with my usage of the file handle/nsurl/something like that??
Your approach of taking the NSURL from array and using stringByReplacingOccurrencesOfString and fileURLWithPath and then description is wrong; it doesn't correctly handle the percent-encoding in the URL and it's generally complex/fragile.
This can be much simpler, because you already have a file URL returned in the array from contentsOfDirectoryAtURL. You can just use it directly:
let data = try String(contentsOfURL: array[0], encoding: NSUTF8StringEncoding)

Resources