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"}}
Related
I have a problem accessing my files.
I am trying to create a file and send it over FTP. However, when I tried to read the file I created, I got this error message. Can you check where did I made a mistake?
The FTP upload was from https://gist.github.com/Nirma/fb9991be776107d17fdcd6ed2aa02876
The TXT file was created successfully with following codes, I can view it on my iPad simulator.
// Create TXTFile
let fileName = "test.txt"
self.save(text: "some text shown here", toDirectory: self.documentDirectory(), withFileName: fileName)
self.read(fromDocumentsWithFileName: fileName)
But the error happens when I execute the FTPupload codes.
// FTP upload
let ftp = FTPUpload(baseUrl: "XXX.XXX.XXX.XXX", userName: "XXXXXXX", password: "XXXXXXX", directoryPath: "XXXXX")
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
***let data = try Data(contentsOf: url as URL, options: [ .alwaysMapped, .uncached])***
ftp.send(data: data , with: "test.txt") { (success) in
print("success")
}
print(data)
}
catch {
print(error)
}
}
I have tracked down that the line with stars creates the error which shows I don't have the permission to view the file.
Can anyone help me? Thanks!
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'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.
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.