Search code examples
swiftnsfilemanager

How to save images in ascending order in swift?


I am building an application in which i am using FileManager to save some images using device camera. So for Now I am saving file name as Doc-Time. I am using below code,

func saveImageToDocumentDirectory(image: UIImage ) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm:ss"
    
    let fileName = "Doc-" + dateFormatter.string(from: Date())
    let fileURL = documentsDirectory.appendingPathComponent(fileName
    )
    if let data = image.jpegData(compressionQuality: 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
        do {
            try data.write(to: fileURL)
            print("file saved")
        } catch {
            print("error saving file:", error)
        }
    }
}

But Here i want to as, Doc-1,Doc-2, Doc-3.... How can i do that?


Solution

  • You can achieve this by simply storing the next index of the image. Like first the index should be 1 when you used named the image as Doc-1 then the index has 2 in it and so on....

    One way to store this index in UserDefaults like:

    var nextImageIndex: Int {
        UserDefaults.standard.integer(forKey: "NextImageIndex") + 1  //+1 if you want to start with 1
    }
        
    func incrementImageIndex() {
        UserDefaults.standard.setValue(nextImageIndex, forKey: "NextImageIndex")
    }
    

    Put the above code somewhere in UIViewController to see it works.

    Here is your updated method...

    func saveImageToDocumentDirectory(image: UIImage ) {
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return
        }
        
        let fileName = "Doc-\(nextImageIndex)"
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        let fileAlreadyExists = FileManager.default.fileExists(atPath: fileURL.path)
        if let data = image.jpegData(compressionQuality: 1.0), !fileAlreadyExists {
            do {
                try data.write(to: fileURL)
                incrementImageIndex()
                print("file saved")
            } catch {
                print("error saving file:", error)
            }
        }
    }