gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:46:32 26 4
gpt4 key购买 nike

我正在从 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!)
}

}

现在我需要存储这些数据来维护 url 的目录结构

我已经尝试过

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

但是我错了

那么如何解决这个问题或者有其他方法可以保存吗?

最佳答案

你尝试过这样的事情吗? :

如果您已经有字符串形式的确切路径:

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

}

关于ios - Swift 数据写入 Document 目录维护目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com