There’s something wonky about the code you’re showing. You seem to be calling a function, listDir(dir:)
, but you’re not showing the definition of that function.
Regardless, you won’t be able to achieve your goal. Swift Playgrounds runs your app is a sandbox and that sandbox prevents access to most stuff on the user’s hard disk. Consider this snippet:
import Foundation
let fileManager = FileManager.default
let libDir = try fileManager.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
print(libDir.path)
It prints:
/Users/quinn/Library/Containers/com.apple.PlaygroundsMac.ExecutionExtension/Data/Library
which is the library directory associated with your sandbox.
Now consider this:
import Foundation
let fileManager = FileManager.default
let realLibDir = URL(fileURLWithPath: "/Library/Logs/DiagnosticReports")
do {
let contents = try fileManager.contentsOfDirectory(at: realLibDir, includingPropertiesForKeys: nil)
print(contents)
} catch {
print(error)
}
It fails with:
Error Domain=NSCocoaErrorDomain Code=257 "The file “DiagnosticReports” couldn’t be opened because you don’t have permission to view it." UserInfo={NSURL=file:///Library/Logs/DiagnosticReports, NSFilePath=/Library/Logs/DiagnosticReports, NSUnderlyingError=0x7fa5007833c0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
Error 1 is EPERM
, which is the sandbox preventing you from accessing stuff outside of your container.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"