如何在Swift 3.0中更新图像的文件目录路径?

时间:2017-05-21 19:55:47

标签: ios swift nsfilemanager

目前我通过创建目录路径并将图像写入该目录来存储图像的文件路径位置,如下所示:

245

func createDirectory() -> String { let fileManager: FileManager = FileManager.default let dirPaths: [URL] = fileManager.urls(for: .documentDirectory, in: .userDomainMask) let docsDir: URL = dirPaths[0] let appDirPath = docsDir.appendingPathComponent("MyApp").path do { try fileManager.createDirectory(atPath: appDirPath, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print("Error: \(error.localizedDescription)") } return appDirPath } func getPath() -> String { let paths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory: String = paths[0].appending("/MyApp") return documentsDirectory } func saveToDocuments() { let fileManager: FileManager = FileManager.default let imageData: Data = UIImageJPEGRepresentation(globalImage, 1.0)! let dateTime: Date = Date() let formatter: DateFormatter = DateFormatter(); formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"; formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale! globalTimeStamp = formatter.string(from: dateTime); globalTimeStamp = globalTimeStamp(of: " ", with: "_") globalTimeStamp = globalTimeStamp + ".jpg" let documentsPath: URL = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let imagePath: URL = documentsPath.appendingPathComponent("MyApp/" + globalTimeStamp) let path = imagePath.path let success = fileManager.createFile(atPath: path as String, contents: imageData, attributes: nil) } 表示图像名称,该名称会附加到我的应用程序目录的路径,并写入文件,如timeStamp所示。

我的问题是,如果我想在我的应用中的其他位置更新createFile,如何更新文件路径以指向 SAME 图像,而不是必须重新创建另一个指向 SAME 图像的文件路径?

谢谢!

1 个答案:

答案 0 :(得分:0)

我不清楚为什么要再次保存同一个文件。它已经保存了。如果您在此期间更改了图像,我建议您删除旧图像并保存新图像。因为经过一段时间而重新保存相同的图像对我来说似乎没有必要。相反,我通过将图像移动到新的文件路径来重命名图像。

这是我在我的一个应用程序中以独特的文件名保存和删除图像的方式,然后我可以在我的应用程序中传递。我知道我还没有实现正确的错误处理,但该代码来自未完成的应用程序:

func saveImageFile(_ image: UIImage) -> String {
    let imageName = FileManager.uniqueImageName()
    try! UIImageJPEGRepresentation(image, 1.0)?.write(to: imageName.imageUrl)
    return imageName
}

func deleteFile(named fileName: String?) {
    guard let imagePath = fileName?.imageUrl.relativePath else { return }
    guard FileManager.default.fileExists(atPath: imagePath) else { return }
    try! FileManager.default.removeItem(atPath: imagePath)
}

extension FileManager {

    private var imageDirectory: URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths.first!
        return documentsDirectory
    }

    static func uniqueImageName() -> String {
        //Try until we get a unique filename
        while(true){
            //Generate a UUID
            let uuid = UUID().uuidString

            //Create the path for the file we want to use
            let filePath = uuid.imageUrl.relativePath

            //Check if the file already exists
            if !FileManager.default.fileExists(atPath: filePath){
                return uuid
            }
        }
    }

    static func urlFor(imageNamed imageName: String) -> URL {
        return FileManager.default.imageDirectory.appendingPathComponent(imageName).appendingPathExtension("jpeg")
    }
}

extension String {
    var imageUrl: URL {
        return FileManager.urlFor(imageNamed: self)
    }
}