Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

How to save an image in a view controller using User defaults in Xcode?

In my program, the user randomly selects an image in the 1st view controller and the selected image is then sent to the 2nd View controller. Now, my question is how can I save that image sent to the 2nd View controller (the saved image will be refreshed if the user selects another image in the 1st View controller) so that I can use it even if I go to another view controller? This is the code of my 1st View Controller and how am I sending the selected image to the 2nd View controller:-

var image1: UIImage!

@IBAction func Button1(_ sender: UIButton) {
         
    image1 = UIImage(named: "image")
    
}
@IBAction func Button2(_ sender: UIButton) {
         
    image1 = UIImage(named: "image")
    
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.destination is 2ndViewController {
        
        let vc2 = segue.destination as! 2ndViewController
        vc2.image2 = image1
    }
}

Upvotes: 0

Views: 153

Answers (1)

YodagamaHeshan
YodagamaHeshan

Reputation: 6500

you cannot save images in userDefaults. so that You can store image name in userDefaults.

and use below methods to save and retrieve images.

saving image

 func saveImage(image: UIImage) -> Bool {
        guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
            return false
        }
        guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
            return false
        }
        do {
            try data.write(to: directory.appendingPathComponent("fileName.png")!)
            return true
        } catch {   
            print(error.localizedDescription)
            return false
        }
    }

retriving image

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
}

Upvotes: 2

Related Questions