Yellow
Yellow

Reputation: 175

How do i save and recall a UIImage on the View Controller?

I am using Swift 3 and have been following apples https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html have created 20 different UIImage views on 20 different UIViewcontroller

They are called photoImageView1 photoImageView2 etc. currently you are able to click on each generic image and input your own image.

I would like the user to be able to input their image but also save it and when they re-open that same viewcontroller the image they inputed is there.

I have looked at many different methods however have been unsuccessful i have attempted following this question Save images in NSUserDefaults? and was once again unsuccessful. Any help would be much appreciated, Thanks.

Upvotes: 0

Views: 493

Answers (2)

Yellow
Yellow

Reputation: 175

i ended up using this method it may not be the best but its easy and it works.

import UIKit


class timetable: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet var imageviewtimetable: UIImageView!

@IBAction func saveMyImage(_ sender: UIBarButtonItem) {

    let myTimeTableImage = imageviewtimetable.image
    let theImageData:NSData = UIImagePNGRepresentation(myTimeTableImage!)! as NSData

    UserDefaults.standard.set(theImageData, forKey: "mySavedImage")

    let data = UserDefaults.standard.object(forKey: "mySavedImage")
    imageviewtimetable.image = UIImage(data: data as! Data)



}




   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.



    let data = UserDefaults.standard.object(forKey: "mySavedImage")
    imageviewtimetable.image = UIImage(data: data as! Data)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func selectImageFromPhotoLibrary(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)


}



func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
    dismiss(animated: true, completion:nil)
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    imageviewtimetable.image = selectedImage

    dismiss(animated: true,completion:nil)
}



/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

Upvotes: 1

Josh Homann
Josh Homann

Reputation: 16327

You can store the image name in a database, iCloud, a plist or even Userdefaults. To save an image to disk, but not the photo library, use:

    import PlaygroundSupport
    import UIKit

    func save(image: UIImage, name: String) -> Bool {
        guard var path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
            let imageData = UIImagePNGRepresentation(image) else {
                return false
        }
        path = path.appendingPathComponent(name)
        do {
            try imageData.write(to: path)
        } catch {
            return false
        }
        return true
    }

    func loadImage(name: String) -> UIImage? {
        guard var path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        path = path.appendingPathComponent(name)
        return UIImage(contentsOfFile: path.relativePath)
    }

    let image = UIImage(named: "test.png")!
    save(image: image, name: "test2.png")
    let loadedImage = loadImage(name: "test2.png")
    PlaygroundPage.current.liveView = UIImageView(image: loadedImage)

EDIT: I changed the source code to a full playground so you can copy and paste it into a playground and run it. The only thing you need to do is drag a file named test.png into the Resources folder.

Upvotes: 0

Related Questions