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

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.

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

Error Domain=NSCocoaErrorDomain Code=257 "The file “Documents” couldn’t be opened because you don’t have permission to view it."

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!

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

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.

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.

Resources