Swift 中的 applicationSupport 文件夹中未创建文本文件
Text File is not being created in applicationSupport folder in Swift
我正在尝试将字符串输入到文本文件中,但是函数 createFile(path:contents:attributes) returns 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")
}
}
应该得到 "The file was created" 但得到 "File is 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")
}
我正在尝试将字符串输入到文本文件中,但是函数 createFile(path:contents:attributes) returns 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")
}
}
应该得到 "The file was created" 但得到 "File is 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")
}