Swift数据写入Document目录维护目录结构

时间:2017-01-10 14:31:32

标签: ios swift firebase firebase-storage

我从firebase下载文件。假设请求网址正在跟随

social-cam-storage/albm-72/owner-2/1484043313786.jpeg

我可以使用以下代码下载文件

func downloadFile(url : String) {
        let storageR = FIRStorage.storage().reference(withPath: url)
        let maxSize : Int64 = 3 * 1024 * 1024  // 3MB

        storageR.data(withMaxSize: maxSize) { (data, error) in
            if error != nil {
                print(error.debugDescription)
                return
            }

            print(data!)
        }

    }

现在我需要存储这些数据,保持网址的目录结构

我试过了

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(FileManager.default.createFile(atPath: "\(documentsURL.absoluteString)/\(url)", contents: data!, attributes: nil))

但我得假了

所以如何解决这个问题还是有其他方法可以保存吗?

2 个答案:

答案 0 :(得分:0)

你尝试过这样的事吗? :

如果您已将确切路径作为字符串:

try? data.write(to: URL(fileURLWithPath: path), options: [.atomic])

如果您需要路径,可以使用以下几种方法:

func saveFile() {
    let filePath = getDocumentsURL().absoluteString.appending(path)
    try? data.write(to: URL(fileURLWithPath: filePath), options: [.atomic])
}

func getDocumentsURL() -> URL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    return documentsURL
}

您也可以尝试保存文件名,然后在需要时加载:

func fileInDocumentsDirectory(_ filename: String) -> String {
    let fileURL = getDocumentsURL().appendingPathComponent(filename)
    return fileURL.path
}

// To save file
func saveFile(data: Data) {
    let fileName:String = "createUniqueFileName"
    let filePath = fileInDocumentsDirectory(fileName)
    saveData(data, filePath)
}

// To load file with saved file name
func loadFile(fileName: String) {

    if let loadedData = loadData(fileName) {
         // Handle data however you wish
    }

}

func saveData(_ data: Data, path: String ) {

    try? data.write(to: URL(fileURLWithPath: path), options: [.atomic])

}

func loadData(_ path: String) -> Data? {

    let data:Data? = try? Data(contentsOf: URL(fileURLWithPath: path))

    return data

}

答案 1 :(得分:0)

您是否尝试过在Firebase存储中使用内置的“download to file”API?

// Create a reference to the file you want to download
let fileURL = storage.reference(withPath: url)

// Create local filesystem URL
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = ... 

// Download to the local filesystem
let downloadTask = islandRef.write(toFile: fileURL) { url, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Local file URL is returned
  }
}