How can I lock a folder in swift? like this
The Locked checkbox in the Finder is implemented at the API level as the UF_IMMUTABLE
flag in chflags
(see its man page, although make sure to look at section 2 of the manual because section 1 has a similarly named page for the chflags
tool). You can see this in Terminal:
% ls -ldO {un,}locked
drwxr-xr-x 2 quinn staff uchg 64 8 Nov 10:00 locked
drwxr-xr-x 2 quinn staff - 64 8 Nov 10:00 unlocked
Setting this from Swift is tricky because none of the standard high-level APIs (FileManager
and URL
) support this. The easiest option, IMO, is to call BSD directly. For example:
import Foundation
func main() {
let u = URL(fileURLWithPath: "/Users/quinn/Test/unlocked")
let success = chflags(u.path, CUnsignedInt(UF_IMMUTABLE)) >= 0
if !success {
let error = NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)
print("failed, error: \(error)")
return
}
print("success")
}
main()
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"