Error Code 513 : you don't have permission to access "Documents" - swift

hello I using NSUelSession to download large files and inside my didFinishDownloadingToUrl in some Devices randomly I am get this error
Error Code 513 : you don't have permission to access "Documents"
when I am trying to move the file to document directory . I can't re-produce this error on my actual device when connected to Xcode how ever this happened on random devices running iOS 13 and 12. what is the problem?
this is my saveFile function
func saveFile(location : URL , fileName : String) {
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let savedURL = documentsPath.appendingPathComponent(fileName)
do {
try self.fileManager.moveItem(atPath: location.relativePath , toPath: savedURL!.relativePath)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
do {
SCLAlertView().showError("File Not Saved", subTitle: "Error Code \. (error.code) : \(error.localizedDescription)")
try fileManager.removeItem(at: location)
}
catch {
print(error.localizedDescription)
}
}
}

Related

Listing all files in a directory on macOS Big Sur

In a different question I asked how to save files on a directory of the user's choosing. The reply was the following code, which works great.
func resolveURL(for key: String) throws -> URL {
if let data = UserDefaults.standard.data(forKey: key) {
var isStale = false
let url = try URL(resolvingBookmarkData: data, options:[.withSecurityScope], bookmarkDataIsStale: &isStale)
if isStale {
let newData = try url.bookmarkData(options: [.withSecurityScope])
UserDefaults.standard.set(newData, forKey: key)
}
return url
} else {
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.canChooseFiles = false
if panel.runModal() == .OK,
let url = panel.url {
let newData = try url.bookmarkData(options: [.withSecurityScope])
UserDefaults.standard.set(newData, forKey: key)
return url
} else {
throw ResolveError.cancelled
}
}
}
func saveFile(filename: String, contents: String) {
do {
let directoryURL = try resolveURL(for: "savedDirectory")
let documentURL = directoryURL.appendingPathComponent (filename + ".txt")
print("saving " + documentURL.absoluteString)
try directoryURL.accessSecurityScopedResource(at: documentURL) { url in
try contents.write (to: url, atomically: false, encoding: .utf8)
}
} catch let error as ResolveError {
print("Resolve error:", error)
} catch {
print(error)
}
}
Now, the next step is to go to the directory the user chose when the app loads, and if any files are there, ready each one and add the contents of those files to the struct I use to hold the data.
Googling a little bit I found that you can read all files in a directory using FileManager.default.contentsOfDirectory so I wrote:
func loadFiles() {
do {
let directoryURL = try resolveURL(for: "savedDirectory")
let contents = try FileManager.default.contentsOfDirectory(at: directoryURL,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles])
for file in contents {
print(file.absoluteString)
}
} catch let error as ResolveError {
print("Resolve error:", error)
return
} catch {
print(error)
return
}
}
But, I get the following error:
Error Domain=NSCocoaErrorDomain Code=257 "The file “myFiles” couldn’t be opened because you don’t have permission to view it." UserInfo={NSURL=file:///Users/aleph/myFiles, NSFilePath=/Users/aleph/myFiles, NSUnderlyingError=0x600000704ba0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
which looking at my code I would guess it's happening because I'm not using directoryURL.accessSecurityScopedResource. I tried to add that, or find any other way, but I'm running into a block and I don't know how to get to the directory saved in savedDirectory, and go through every file, reading its contents.
Thank you for any help
If I use:
directoryURL.startAccessingSecurityScopedResource()
// load the files
directoryURL.stopAccessingSecurityScopedResource()
Then it works.

SwiftUI macOS Sandboxed application active read the .ssh/config file

I have Sandboxed application active I need to read the following .ssh/config file.
But I am having the following error:
Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=260
"The file “config” couldn’t be opened because there is no such file."
UserInfo={NSFilePath=/Users/name/Library/Containers/sa.GitRepository/Data//.ssh/config,
NSUnderlyingError=0x600003ccf120 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Can you tell me how I can solve the problem?
Code:
guard let desktopPath = NSSearchPathForDirectoriesInDomains(.desktopDirectory,
.userDomainMask,
true).first else { return }
_path = State(initialValue: desktopPath)
let pathConfig = desktopPath.replacingOccurrences(of: "Desktop", with: "/.ssh/config")
do {
let contents = try String(contentsOfFile: pathConfig, encoding: .utf8)
let myStrings = contents.components(separatedBy: .newlines)
let users = myStrings.filter { $0.contains("github.com-") }.map {$0.replacingOccurrences(of: "Host github.com-", with: "")}
if(users.count > 0){ _user = State(initialValue: users[0]) }
_userArray = State(initialValue: users)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

Any information on MCMErrorDomain error 44?

I am running into "MCMErrorDomain error 44" about 50% of the time on app.launch() when loading a container to my app. I have no idea what is the cause and I can't find any information about this error.
This is the code I am using to load container to the app.
extension AppDelegate {
func loadAppData(appDataPath: String) {
let loaderUrl = URL(fileURLWithPath: #file)
let bundleUrl = URL(fileURLWithPath: appDataPath, relativeTo: loaderUrl).appendingPathExtension("xcappdata")
let contentsURL = bundleUrl.appendingPathComponent("AppData")
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(at: contentsURL,
includingPropertiesForKeys: [.isDirectoryKey],
options: [],
//swiftlint:disable:next force_unwrapping
errorHandler: nil)!
//swiftlint:disable:next force_unwrapping
let destinationRoot = fileManager.urls(for: .libraryDirectory, in: .userDomainMask).last!.deletingLastPathComponent()
let test = fileManager.enumerator(at: destinationRoot,
includingPropertiesForKeys: [.isDirectoryKey],
options: [],
//swiftlint:disable:next force_unwrapping
errorHandler: nil)!
while let lol = test.nextObject() as? URL {
do {
try fileManager.removeItem(at: lol)
} catch {
print("✌️ \(error)")
}
}
print("✌️ \(destinationRoot)")
let sourceRoot = contentsURL.standardizedFileURL.path
while let sourceUrl = enumerator.nextObject() as? URL {
guard let resourceValues = try? sourceUrl.resourceValues(forKeys: [.isDirectoryKey]),
let isDirectory = resourceValues.isDirectory,
!isDirectory else {
continue
}
let path = sourceUrl.standardizedFileURL.path.replacingOccurrences(of: sourceRoot, with: "")
let destinationURL = destinationRoot.appendingPathComponent(path)
do {
try fileManager.createDirectory(at: destinationURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil)
try fileManager.copyItem(at: sourceUrl,
to: destinationURL)
} catch {
print("✌️ \(error)")
do {
_ = try fileManager.replaceItemAt(destinationURL, withItemAt: sourceUrl)
} catch {
print("✌️ \(error)")
}
}
}
print("done")
}
}
Yes, MCMErrorDomain is frustrating, as it not documented by Apple.
When I encounter it, the full description reads:
The test runner encountered an error (Failed to install or launch the
test runner. (Underlying error: The operation couldn’t be completed.
(MCMErrorDomain error 44.)))
The workaround I found is to delete the app from simulator and re-run the test.
So far, here is what I am learning about this particular error:
it looks as it is coming from MobileContainerManager.framework
often caused by interrupting a running test on simulator.
once it happens the simulator often in permanently "damaged" state until app is deleted.
only happens for Application tests, that require host app, never for Logic tests.
happens only at the beginning of a test suite
often caused by Xcode Bot trying to use the same simulator that Xcode is already using.
Framework Location:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/MobileContainerManager.framework
shows entries for MCMErrorDomain in MobileContainerManager binary and in containermanagerd

NSCocoaErrorDomain Code=257 file couldn’t be opened because you don’t have permission to view it : FileManager attributesOfItem returns nil in iOS13

FileManager returns permission error while trying to get the file size, in iOS 13 devices.
do {
let attr = try FileManager.default.attributesOfItem(atPath: my_file_path) //--> Getting nil
fileSize = attr[FileAttributeKey.size] as! UInt64
} catch {
print("Error: \(error)")
}
Error returned:
Error Domain=NSCocoaErrorDomain Code=257 "The file “trim.1A9FFC19-EE2C-438A-BF3D-97E05A97EF9E.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Containers/Data/PluginKitPlugin/ADB8684E-12B5-451D-A20F-158B899BB3DD/tmp/trim.1A9FFC19-EE2C-438A-BF3D-97E05A97EF9E.MOV, NSUnderlyingError=0x280af0510 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
The issue observed only after I updated to iOS 13. In earlier versions everything is working fine.
iOS 13 SDK consider photo app as an another app, so when we dismiss the image picker controller video url will be invalidate.
I had the problem before when I try to upload video to AWS, what i did just create a temporary folder and copy the existing video url path before dismiss the Image-picker.then it upload, it's worked.
func createDirectory(videoURL:URL){
let Directorypath = getDirectoryPath()
var objcBool:ObjCBool = true
let isExist = FileManager.default.fileExists(atPath:Directorypath,isDirectory: &objcBool)
// If the folder with the given path doesn't exist already, create it
if isExist == false{
do{
try FileManager.default.createDirectory(atPath: Directorypath, withIntermediateDirectories: true, attributes: nil)
}catch{
print("Something went wrong while creating a new folder")
}
}
let fileManager = FileManager()
do {
if fileManager.fileExists(atPath:Directorypath) {
try? fileManager.removeItem(at: URL(fileURLWithPath:Directorypath))
}
try fileManager.copyItem(at:videoURL.absoluteURL, to: URL(fileURLWithPath:Directorypath))
self.imagePicker.dismiss(animated: true, completion:nil)
}catch let error {
print(error.localizedDescription)
}
}

Unable to unzip a downloaded file

I created a route on my nodejs server that sends a zip file of images. But unfortunately every time I make a request to the server I am able to download the zip file to but I can seem to be able to unzip file. I get the error message "unarchivable" and localized description of the error message is "The operation couldn’t be completed. (Zipper.Zipper.ArchiveError error 0.)" The nodejs route works perfectly fine with postman and my Android app.
Alamofire: 5.0.0-beta.5
swift: 4.2
I found this
Unzipping Error The operation couldn’t be completed. (Zip.ZipError error 1.) between ViewControllers
but I couldn't make sense it. I did try using a completion handler for the download process but still got the same error message
// swift code
do {
try FileManager.default.createDirectory(at: self.getDocumentsDirectory().appendingPathComponent("zipServe"), withIntermediateDirectories: true, attributes: nil)
let destination: DownloadRequest.Destination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("zipServe").appendingPathComponent("pig.zip")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
AF.download(self.main_url + "imagesAll/shop/", method: HTTPMethod.post, parameters: parameters, headers: headers, to: destination)
.downloadProgress { progress in
print("Download Progress: \(progress.isFinished)")
}
.response { response in
if response.error == nil, let imagePath = response.fileURL {
do {
print(imagePath)
if FileManager.default.fileExists(atPath: imagePath.path) {
print("File exists")
try FileManager().unzip(item: imagePath.absoluteURL, to: self.getDocumentsDirectory().appendingPathComponent("zipServe"))
} else {
print("File not found")
}
} catch let error {
print(error.localizedDescription)
}
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
I should be able to see a list of the images contained within the zip file.