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

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

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.

Permissions error renaming a file on disk

I am trying to rename a file on the local hard disk from a swift MacOS application.
Basically I am bringing up the open panel to select the folder where the files are. then I enumerate the files and rename them to the modification date.
Here is the relevant code:
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false
var mtsVideosFolderPathString : String! = ""
if openPanel.runModal() == NSApplication.ModalResponse.OK
{
mtsVideosFolder = openPanel.urls[0] as URL
mtsVideosFolderPathString = mtsVideosFolder?.path
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(atPath: mtsVideosFolderPathString)
while let element = enumerator?.nextObject() as? String
{
if element.hasSuffix("MTS")
{
let filePath = "\(mtsVideosFolderPathString!)/\(element)"
let fileModDate = self.fileModificationDate(url: URL(fileURLWithPath: filePath))
let format = DateFormatter()
format.timeZone = .current
format.dateFormat = "yyyy.MM.dd HH.mm.ss"
let dateString = format.string(from: fileModDate!)
let fromFilename = "\(mtsVideosFolderPathString!)/\(element)"
let toFilename = "\(mtsVideosFolderPathString!)/\(dateString).mts"
print("Rename \(fromFilename) to \(toFilename)")
do {
try fileManager.moveItem(at: URL(fileURLWithPath: fromFilename), to: URL(fileURLWithPath: toFilename))
}
catch let error as NSError
{
print("Ooops! Something went wrong: \(error)")
}
}
}
}
When I run the app its fails at moveItem in the try/catch with the following error:
Rename /Volumes/BigNFast/test/00000.mts to /Volumes/BigNFast/test/2013.08.05 20.09.50.mts
Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=513 "“00000.mp4” couldn’t be moved because you don’t have permission to access “ test”." UserInfo={NSSourceFilePathErrorKey=/Volumes/BigNFast/test/00000.mp4, NSUserStringVariant=(
Move
), NSDestinationFilePath=/Volumes/BigNFast/test/2013.08.05 20.09.50.mp4, NSFilePath=/Volumes/BigNFast/test/00000.mp4, NSUnderlyingError=0x6000002bb450 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
So, the question is, how do I set the permissions? How to I rename a file on disk?
Thank you for any help
Signing and Capabilities -> File Access -> User Selected File
Change it to read and write with the selector.

SwiftUI macOS add costum file format (UTI)

I have a "normal" swiftUI macOS project, and I need to read some "custom" files like data.dat and data.DCA.
How do I add these extensions to my Xcode project?
At the moment I use the following code to read the data, but for non standard file extensions I just get the error: Error Domain=NSCocoaErrorDomain Code=260 "The file “test.dat” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/UserName/*/RandomAppName/test.dat, NSUnderlyingError=0x600001af0450 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
let userName = NSUserName()
let path = "/Users/\(userName)/*/RandomAppName/test.dat"
var savedData = Data()
var savedString = String()
do {
let url = URL(fileURLWithPath: path)
savedData = try Data(contentsOf: url)
if let ssavedString = String(data: savedData, encoding: .utf8) {
savedString = ssavedString
print(savedString)
}
} catch {
print(error)
}

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

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

Error deleting contents in directory - Domain=NSCocoaErrorDomain Code=4 | Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"

How can I fix the following errors when running the code below? I already searched in SO but can't find anything for Swift 3.
// Delete all files in given directory
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let dataPath = NSURL(fileURLWithPath: path)
if let enumerator = FileManager.default.enumerator(atPath: dataPath.path!) {
while let fileName = enumerator.nextObject() as? String {
do {
try FileManager.default.removeItem(atPath: "\(dataPath)\(fileName)")
}
catch let e as NSError {
print(e)
}
catch {
print("error")
}
}
}
Log:
Error Domain=NSCocoaErrorDomain Code=4 "“.DS_Store” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/.DS_Store, NSUserStringVariant=(
Remove
), NSUnderlyingError=0x60800004fed0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Error Domain=NSCocoaErrorDomain Code=4 "“2017-01-31_10-44-21.m4a” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/2017-01-31_10-44-21.m4a, NSUserStringVariant=(
Remove
), NSUnderlyingError=0x60800004fa80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Error Domain=NSCocoaErrorDomain Code=4 "“2017-01-31_10-44-26.m4a” couldn’t be removed." UserInfo={NSFilePath=file:///Users/CIPL0469/Library/Developer/CoreSimulator/Devices/F0106B28-C4D1-4FE2-A425-D04C6BFDDC01/data/Containers/Data/Application/A5AB9B7B-6174-4BA7-9EFD-0E9F1C98CB17/Documents/2017-01-31_10-44-26.m4a, NSUserStringVariant=(
Remove
), NSUnderlyingError=0x60000004f570 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
nextObject() of (NS)DirectoryEnumerator returns always the full path / url of the enumerated items, an additional concatenation breaks the path. Aside form that concatenating URL and String with String Interpolation to pass it as path parameter doesn't work at all.
I recommend to use the URL related API anyway
let fileManager = FileManager.default
do {
let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
while let fileURL = enumerator.nextObject() as? URL {
try fileManager.removeItem(at: fileURL)
}
}
} catch {
print(error)
}
Just to make it clear:
let addr = one["resourceAddr"] as! String
do {
try FileManager.default.removeItem(at: URL(string:addr)!)
} catch let error as NSError {
print("error: ", error.localizedDescription)
}
It is mostly happening because the file you are trying to read at URL does not exist.