0

I am working on an app where I am trying to write data to a file. Basically the user can set the save directory and then I want to be able to check to see if the file exists. If it doesn't then create it and write the data. If it does exist I want to update/append a string to the end of the file. I have tried following many examples and guides online and it seems everyone is doing this differently. I apologize ahead of time if I am missing something super simple or if this has been asked a hundred times.

I have mostly been working off of this example with no success Append text or data to text file in Swift

@IBAction func addVariance(_ sender: Any) {
    let csvString = "08-06-2019,10:00 AM,10:23 AM,23,Offline,Test"
    let directoryURL = URL(string: "/Users/username/Desktop/CSVtest")
    let fileURL = directoryURL!.appendingPathComponent("/variances.csv")
    let data = NSData(data: csvString.data(using: String.Encoding.utf8, allowLossyConversion: false)!)
    if FileManager.default.fileExists(atPath: fileURL.path) {
        var err:NSError?
        if let fileHandle = try? FileHandle(forUpdating: fileURL) {
            fileHandle.seekToEndOfFile()
            fileHandle.write(data as Data)
            fileHandle.closeFile()
        }
        else {
            print("Can't open fileHandle \(String(describing: err))")
        }
    }
    else {
        var err:NSError?
        do {
            try data.write(to: URL(fileURLWithPath: fileURL.path), options: .atomic)
        } catch {
            print(error)
        }
    }
}

When trying to run this function when there is a file in the folder named "variances.csv" I get "Can't open fileHandle nil".

I have tried break points and print() lines. It doesn't seem to be getting past "if let fileHandle = try? FileHandle(forUpdating: fileURL)" and I can't figure out why. fileURL is not nil.

When I try running this function outputting to an empty directory I get.

"Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “variances.csv” in the folder “CSVtest”." UserInfo={NSFilePath=/Users/username/Desktop/CSVtest/variances.csv, NSUnderlyingError=0x600000c9eaf0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}"

kiddslopp
  • 95
  • 1
  • 8
  • Use `URL(fileURLWithPath:)`, not `URL(string:)`. – rmaddy Aug 06 '19 at 15:48
  • I changed it from URL(string:) to URL(fileURLWithPath:) on line 3 but it still gives me the same error. – kiddslopp Aug 06 '19 at 15:53
  • `Desktop` is not accessible out of the box if the app is sandboxed. Only the standard `Downloads`, `Pictures`, `Music` and `Movies`. https://stackoverflow.com/a/51311426/584548 – backslash-f Aug 06 '19 at 15:55
  • Is there anyway around that? Can I give the app full disk access somehow? – kiddslopp Aug 06 '19 at 16:08
  • If the app is sandboxed there is no workaround unless the user chooses the folder once in an open dialog and you set a security scoped bookmark. – vadian Aug 06 '19 at 16:17
  • This sounds like exactly what I need. I already have the open dialog to select the save directory. Got any good resources for the security scoped bookmark? – kiddslopp Aug 06 '19 at 16:18
  • 1
    [App Sandbox in Depth](https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html) – vadian Aug 06 '19 at 16:18

0 Answers0