How to save an image picked from a UIImagePickerController in Swift?

前端 未结 2 615
独厮守ぢ
独厮守ぢ 2021-01-07 00:13

I\'m building an app where I let the user to pick an image from its photo library. I was using this code to save it.

func imagePickerController(picker: UIIma         


        
2条回答
  •  逝去的感伤
    2021-01-07 01:06

    There are two ways, one that you are describing but that is quite messy, the one I would suggest you is to take the image, turn into image data and store it in your application locally like in a sqlite database or in an array in user default. However saving that much data in user default is not a good practise. So, I would go with store it locally and I won't do it with messy sqlite codes, rather I would do it with core data.

    class AddImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        @IBOutlet var popUpThePickerButton: UIButton! //click on this button to appear the imagePicker
        @IBOutlet var addPictureButton: UIButton! //when this button clicked saveImage method is called and there you save the imageData wherever you want
    
        let picker = UIImagePickerController()
        var selectedImage : UIImage!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            picker.delegate = self
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    
        // when popUpThePickerButton is clicked
        @IBAction func selectPictureFromPhotos(sender: UIButton) { 
            picker.editing = false
            picker.sourceType = .PhotoLibrary
    
            presentViewController(picker, animated: true, completion: nil)
        }
    
        func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
            self.selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage 
            dismissViewControllerAnimated(true, completion: nil)
        }
    
        func imagePickerControllerDidCancel(picker: UIImagePickerController) {
            dismissViewControllerAnimated(true, completion: nil)
        }
    
    // then save this image data in your database and when you want to show that image you can just turn the image data to image again
    
        @IBAction func saveImage(sender: UIButton) {
            let imageData = UIImagePNGRepresentation(self.selectedImage)
            //save this image data in database
        }
    }
    

提交回复
热议问题