将文件保存在swift 3的文档目录中?

将文件保存在swift 3的文档目录中?

问题描述:

我使用以下代码将文件保存在swift 3的文档目录中:

I am saving files in a document directory in swift 3 with this code:

fileManager = FileManager.default
// let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
path = path + name

let image = #imageLiteral(resourceName: "Notifications")
let imageData = UIImageJPEGRepresentation(image, 0.5)
let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil)

print("bool is \(bool)")
return true

但是正如您所看到的,我没有使用 filemanager 来将文档目录路径作为 filemanager 只给出URL而不是字符串。

But as you can see, I am not using filemanager to get document directory path as filemanager gives only URL not string.

问题:


  • 如何从文件管理器获取字符串?

  • 我的代码中是否有崩溃的可能性?

请反思。

URL 是处理文件路径的推荐方法,因为它包含用于追加和删除路径组件的所有便捷方法扩展 - 而不是字符串 Apple从中删除了这些方法。

URL is the recommended way to handle file paths because it contains all convenience methods for appending and deleting path components and extensions – rather than String which Apple removed those methods from.

不鼓励您连接像 path = path + name 。这很容易出错,因为你负责所有斜杠路径分隔符。

You are discouraged from concatenating paths like path = path + name. It's error-prone because you are responsible for all slash path separators.

此外,你不需要用 FileManager $创建一个文件C $ C>。 数据有一种方法可以将数据写入磁盘。

Further you don't need to create a file with FileManager. Data has a method to write data to disk.

let fileManager = FileManager.default
do {
    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
    let fileURL = documentDirectory.appendingPathComponent(name)
    let image = #imageLiteral(resourceName: "Notifications")
    if let imageData = UIImageJPEGRepresentation(image, 0.5) {
        try imageData.write(to: fileURL)
        return true
    }
} catch {
    print(error)
}
return false