skip to Main Content

I have an entity named Item. I have an export function that exports all Items to CSV. So name, weight, quantity and etc is all exported correctly. The purpose of this is to save the data so that it may be imported later if all the data was deleted. One of the attributes of Items is a picture that the user chooses from its own library. How do I export that picture, so that it can be reimported later?

This is on iOS using the latest swift and Xcode.

I know I have not included any code, I am mainly asking for a direction to look. I’m not sure if I can get the location of the image on the device and then save that to the CSV or if there’s a similar way. Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    So I solved this problem using the code below but I may have created a new one. I'll be posting a new question to better clarify

    The code below allowed me to save to Documents which allowed me to export and import the images.

     func saveImage(image: UIImage, string: String) -> Bool {
        guard let data = image.jpegData(compressionQuality: 1) ?? image.pngData() else {
            return false
        }
        guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
            return false
        }
        do {
            print(string)
            try data.write(to: directory.appendingPathComponent(string)!)
            print("Success - (string)")
            return true
        } catch {
            print(error.localizedDescription)
            return false
        }
    }
    
    func getSavedImage(named: String) -> UIImage? {
        if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
            return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
        }
        return nil
    }
    

  2. CSV is a text based file format but Images are binary data. So the two does not mix well.

    One thing you can do is convert the image to Base64 String and insert that string to the CSV. But the string would be too large and there may be consequences.

    If you are using the same device (probably not) you can get the path of the image and append it to the CSV.

    If you are using a DB simply upload your images to it and add the path to the CSV. (you can even upload the images to your drive and add the path)

    There may be other ways also.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search