在Swift 3中如何将文件保存到文档目录?

42

我正在使用以下代码在Swift 3中将文件保存到文档目录:

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而不是字符串。

问题:

  • 如何从文件管理器中获取字符串?
  • 我的代码有崩溃的可能吗?

let fileManager = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.path - Willjay
4个回答

99

请换个角度思考。

URL 是处理文件路径的推荐方式,因为它包含了所有方便的方法来添加和删除路径组件和扩展名 - 而 String 则从中删除了这些方法。

不建议像 path = path + name 这样拼接路径。这很容易出错,因为您需要负责所有斜杠路径分隔符。

此外,您不需要使用 FileManager 创建文件。 Data 有一个将数据写入磁盘的方法。

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 = image.jpegData(compressionQuality: 0.5) {
        try imageData.write(to: fileURL)
        return true
    }
} catch {
    print(error)
}
return false

或者将函数设为 throw 并将错误交给调用者处理

func saveFile(with name: String) throws {
    let fileManager = FileManager.default
    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let fileURL = documentDirectory.appendingPathComponent(name)
    let image = #imageLiteral(resourceName: "Notifications")
    guard let imageData = image.jpegData(compressionQuality: 0.5) else { throw URLError(.cannotDecodeContentData) }
    try imageData.write(to: fileURL)
}

4
应该有一个检查 if fileManager.fileExists(atPath: path) { print("File already there") } 来判断文件是否已经存在。 - Jack
我能将整个带有图片的文件夹保存到文档目录中吗? - Khushbu Desai
@vadian,你能帮我一下吗?我会分享我的代码,我的文件夹已经复制到文档目录中,但是没有数据。 - Khushbu Desai
这里发生了什么事情: 'let image = #imageLiteral(resourceName: "Notifications")'resourceName代表什么? - Moondra
1
@jack https://forums.developer.apple.com/thread/97497 --> “it is generally regarded as incorrect”等等。你对此有何看法? - Kheldar
显示剩余2条评论

5
我使用以下方法创建“Test.txt”文件。希望对您有所帮助。
func createFile() {
    let fileName = "Test"
    let documentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let fileURL = documentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
    print("File PAth: \(fileURL.path)")
}

5

根据vadian提供的示例,只需要以下一行代码即可将(Data)文件保存在文档目录中:

try imageData.write(to: fileURL)

获取文件路径是有趣的部分。

例如:创建文件路径。

 func createNewDirPath( )->URL{ 

let dirPathNoScheme = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String

    //add directory path file Scheme;  some operations fail w/out it
    let dirPath = "file://\(dirPathNoScheme)"
    //name your file, make sure you get the ext right .mp3/.wav/.m4a/.mov/.whatever
    let fileName = "thisIsYourFileName.mov"
    let pathArray = [dirPath, fileName]
    let path = URL(string: pathArray.joined(separator: "/"))

    //use a guard since the result is an optional
    guard let filePath = path else {
        //if it fails do this stuff:
        return URL(string: "choose how to handle error here")!
    }
    //if it works return the filePath
    return filePath
}

调用函数:

let shinnyNewURLpath = createNewDirPath( ) 


//write data to file using one line in do/catch operation
do {
   try yourDataObject?.write(to: shinnyNewURLpath)
    } 
catch {
       print("catch error",error.localizedDescription)
 }

-14
func copyandpaste() {
   var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
   let dbpath: NSString = path[0] as NSString
        
   let strdbpath =  dbpath.strings(byAppendingPaths: ["mydb.db"])[0]
   print(strdbpath)
   let fmnager  =  FileManager.default
        
   if !fmnager.fileExists(atPath: strdbpath) {
      let local  = Bundle.main.path(forResource: "mydb", ofType: "db")
      do {
         try fmnager.copyItem(atPath: local!, toPath: strdbpath)
      } catch {
      }
   }        
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接