Read text file with Swift

I am completely new to coding on a Mac so excuse the naive questions. I am using Monterey 12.2.1 and Xcode 13.2.1 The following code results in an error: Error: The file “ErrCodes.txt” couldn’t be opened because you don’t have permission to view it.

     let filename = "ErrCodes"      let DesktopDirURL = try! FileManager.default.url(for: .desktopDirectory,in: .userDomainMask,appropriateFor: nil,create:true)      let fileURL=DesktopDirURL.appendingPathComponent(filename).appendingPathExtension("txt")      print("fileURL: = (fileURL)")      var readString = "" // Used to store the file contents      do {        // Read the file contents        readString = try String(contentsOf: fileURL)      } catch let error as NSError {        print("Failed reading from URL: (fileURL), Error: " + error.localizedDescription)      }      print("File Text: (readString)")

The file “ErrCodes.txt” is on the desktop and is printable by terminal and accessible by TextEdit.

What am I doing wrong. Any help would be appreciated.

Thank You

Please, use code formatting tool to make code readable.

let filename = "ErrCodes"
let DesktopDirURL = try! FileManager.default.url(for: .desktopDirectory,in: .userDomainMask,appropriateFor: nil,create:true)     
let fileURL=DesktopDirURL.appendingPathComponent(filename).appendingPathExtension("txt")     
print("fileURL: = (fileURL)")     
var readString = "" // Used to store the file contents     
do {       // Read the file contents
    readString = try String(contentsOf: fileURL)
     } catch let error as NSError {
      print("Failed reading from URL: (fileURL), Error: " + error.localizedDescription) 
    }

print("File Text: (readString)")

Probably your app is sandboxed.

So you need first to get authorisation to get access to the folder (desktop) by using NSOpenPanel()

Read text file with Swift
 
 
Q