【问题标题】:Save file in document directory in swift 3?在swift 3中将文件保存在文档目录中?
【发布时间】:2017-11-22 14:12:36
【问题描述】:

我正在使用以下代码将文件保存在 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

标签: ios swift nsfilemanager nsdocumentdirectory


【解决方案1】:

请反过来想。

URL 是处理文件路径的推荐方法,因为它包含用于附加和删除路径组件和扩展的所有便捷方法,而不是 Apple 已从中删除这些方法的 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

【讨论】:

  • 一张支票if fileManager.fileExists(atPath: path) { print("File already there") }应该在那里。
  • 我可以在文档目录中保存带有图像的整个文件夹吗?
  • @KhushbuDesai 是的,我想。
  • @vadian 你能帮我解决这个问题吗?我将分享我的代码,我的文件夹复制到 doc 目录但没有数据。
  • @jack forums.developer.apple.com/thread/97497 --> “它通常被认为是不正确的”等等。您对此有何看法?
【解决方案2】:

按照 vadian 给出的上述示例,您需要在文档目录中保存(数据)文件的唯一行是:

尝试 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)
 }

【讨论】:

    【解决方案3】:

    我使用以下方法创建“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)")
    }
    

    【讨论】:

      【解决方案4】:
      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 {
            }
         }        
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-13
        • 2016-06-24
        • 1970-01-01
        • 2014-09-10
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 2017-05-30
        • 2013-07-17
        相关资源
        最近更新 更多