我正在使用带有以下代码的 createDirectory 创建新文件夹。
*let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/MyNewFolder"
print("Path\(dataPath)")
if !FileManager.default.fileExists(atPath: dataPath) {
// Creates that folder if no exists
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}*
Run Code Online (Sandbox Code Playgroud)
现在我想在“MyNewFolder”下存储像 log.text 这样的新文件。任何人都可以建议我如何在“MyNewFolder”文件夹下保存新文件
提前致谢。
NSSearchPathForDirectoriesInDomains已经过时了。推荐的API是URL相关的APIFileManager
let folderName = "MyNewFolder"
let fileManager = FileManager.default
let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let folderURL = documentsFolder.appendingPathComponent(folderName)
let folderExists = (try? folderURL.checkResourceIsReachable()) ?? false
do {
if !folderExists {
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: false)
}
let fileURL = folderURL.appendingPathComponent("log.txt")
let hello = Data("hello".utf8)
try hello.write(to: fileURL)
} catch { print(error) }
Run Code Online (Sandbox Code Playgroud)
强烈建议您不要通过连接字符串来构建路径。
| 归档时间: |
|
| 查看次数: |
1836 次 |
| 最近记录: |