【问题标题】:How to retrieve a saved image using its name?如何使用名称检索保存的图像?
【发布时间】:2021-08-04 20:48:35
【问题描述】:

我目前正在使用FileManager 保存图像,如下所示:

guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileName = imageName
let fileURL = documentsDirectory.appendingPathComponent(fileName)
guard let data = image.jpegData(compressionQuality: 0.8) else { return }

do {
    try data.write(to: fileURL)
} catch let error {
    print("error saving file with error", error)
}

我如何使用文件名沿以下类似行检索这个文件?

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("fileName") {
    let filePath = pathComponent.path
    let fileManager = FileManager.default
    // ??
} else {
    print("file not available")
}

【问题讨论】:

    标签: ios swift nsfilemanager


    【解决方案1】:

    使用与save 代码中相同的 URL 相关 API

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileName = "fileName.jpg"
    let fileURL = documentsDirectory.appendingPathComponent(fileName)
    
    if let image = UIImage(contentsOfFile: fileURL.path) {
        // do something with the image
    } else {
        print("error loading file")
    }
    

    【讨论】:

      【解决方案2】:

      如果您想要UIImage,您可以使用init(contentsOfFile:) init(data:)init(data:scale:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-22
        • 2019-10-03
        • 1970-01-01
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多