gpt4 book ai didi

swift - iOS9 FileManager 文件权限改变

转载 作者:可可西里 更新时间:2023-11-01 01:38:59 25 4
gpt4 key购买 nike

将我的应用程序切换到 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)")
}
}

关于swift - iOS9 FileManager 文件权限改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com