将文件保存在swift 3的文档目录中? [英] Save file in document directory in swift 3?

查看:255
本文介绍了将文件保存在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.

不鼓励您连接像<$ c这样的路径$ c> 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 数据有一种方法可以将数据写入磁盘。

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

这篇关于将文件保存在swift 3的文档目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆