iOS9 FileManager File permissions change

社会主义新天地 提交于 2020-01-15 01:48:17

问题


After switching my application to iOS9 I started to get errors that the files I was writing were not readable. Here is how I create the files

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!")
}

When I do this I keep seeing failed!.


回答1:


The original code is just wrong. You need to use the octal representation of the permissions:

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

Correct code:

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!")
}

A function I used to test all possible permissions.

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)")
    }
}


来源:https://stackoverflow.com/questions/32662729/ios9-filemanager-file-permissions-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!