我试图在文本文件中输入一个字符串,但函数 createFile(path:contents:attributes) 返回 false 表示该文件没有被创建。我在应用程序支持目录中创建很累,但是即使我尝试使用 documentDirecorty,我也会得到相同的结果,表明该文件没有被创建。不知道我做错了什么。
let filePin = "userPass.txt"
let _string = "password"
let encrypted = _string.toHexString()
let fileMngr = FileManager.default
let path = fileMngr.urls(for: FileManager.SearchPathDirectory.applicationSupportDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent(self.filePin)
if let data = encrypted.data(using: String.Encoding.utf8) {
if fileMngr.createFile(atPath: (path?.absoluteString)!, contents: data, attributes: nil){
print("The file was created")
}
else {
print("File was not created")
}
}
应该得到“文件已创建”,而是得到“文件未创建”
除了错误的 API absoluteString
,应用程序支持文件夹可能不存在。
这个比较靠谱
let string = "password"
let encrypted = string.toHexString()
let fileManager = FileManager.default
do {
let applicationSupportDirectory = try fileManager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileUrl = applicationSupportDirectory.appendingPathComponent(self.filePin)
let data = Data(encrypted.utf8)
try data.write(to: fileUrl)
print("The file was created")
} catch {
print(error, "File was not created")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句