iOS9 FileManager 文件权限更改

iOS9 FileManager File permissions change

将我的应用程序切换到 iOS9 后,我开始收到错误消息,指出我正在编写的文件不可读。这是我创建文件的方式

let fileManager = NSFileManager.defaultManager()

let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let path = "\(directory)/file.txt"

let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: 666)]
let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)
if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
    NSLog("Worked!")
} else {
    NSLog("Failed!")
}

当我这样做时,我总是看到失败!

原来的代码是错误的。您需要使用权限的八进制表示:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/octal-literal

正确代码:

let fileManager = NSFileManager.defaultManager()

let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let path = "\(directory)/file.txt"

let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: 0o666)]
let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)
if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
    NSLog("Worked!")
} else {
    NSLog("Failed!")
}

我用来测试所有可能权限的函数。

func testPermissions() {
    let types: [Int16] = [0o666, 0o664, 0o662, 0o660, 0o646, 0o626, 0o606, 0o466, 0o266, 0o066]
    for t in types {
        testCreateFile(t)
    }
}

func testCreateFile(permissions: Int16)  {
    let attributes: [String:AnyObject] = [NSFilePosixPermissions: NSNumber(short: permissions)]

    let directory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let filename = "filename\(permissions.description)"
    let path = "\(directory)/\(filename)"

    let fileManager = NSFileManager.defaultManager()
    let success = fileManager.createFileAtPath(path, contents: nil, attributes: attributes)

    if success && fileManager.isWritableFileAtPath(path) && fileManager.isReadableFileAtPath(path) {
        let octal = String(format:"%o", permissions)
        NSLog("It worked for \(octal)")
    }
}