将我的应用程序切换到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!")
}
当我这样做时,我一直看到失败!。
答案 0 :(得分:1)
原始代码是错误的。您需要使用权限的八进制表示:
正确的代码:
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)")
}
}