iOS9 FileManager文件权限更改 [英] iOS9 FileManager File permissions change

查看:418
本文介绍了iOS9 FileManager文件权限更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将应用程序切换到iOS9后,我开始收到错误,提示正在写入的文件不可读.这是我创建文件的方式

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!.

推荐答案

原始代码是错误的.您需要使用权限的八进制表示形式:

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

正确的代码:

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

这篇关于iOS9 FileManager文件权限更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆