jazzedge
11/29/2017 - 4:57 PM

Swift - Photo Select method

01. Begin by declaring that the View Controller class implements the 
UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols, 
then within the ViewController.swift file  implement the code as follows:

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
.
.
@IBAction func selectPhoto(_ sender: AnyObject) {

    let imagePicker = UIImagePickerController()

    imagePicker.delegate = self
    imagePicker.sourceType =
           UIImagePickerControllerSourceType.photoLibrary
    imagePicker.mediaTypes = [kUTTypeImage as String]

    self.present(imagePicker, animated: true,
                     completion:nil)
}
.
.
}

02. Next, implement the delegate methods which will be called when the user has 
either made a photo selection or cancels the selection process:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    self.dismiss(animated: true, completion: nil)
    let image =
        info[UIImagePickerControllerOriginalImage] as! UIImage
    imageView.image = image
    photoURL = saveImageToFile(image)
}

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

03. In both cases the image picker view controller is dismissed from view. 
In the case of a photo being selected, the image is displayed within the application 
via the Image View instance before being written to the file system of the device 
and the corresponding URL stored in the photoURL variable for later reference. 
Clearly the code expects the image file writing to be performed by a method named 
saveImageToFile which must now be implemented:

func saveImageToFile(_ image: UIImage) -> URL
{
    let filemgr = FileManager.default

    let dirPaths = filemgr.urls(for: .documentDirectory,
                                in: .userDomainMask)

    let fileURL = dirPaths[0].appendingPathComponent("currentImage.jpg")

    if let renderedJPEGData =
                UIImageJPEGRepresentation(image, 0.5) {
        try! renderedJPEGData.write(to: fileURL)
    }

    return fileURL
}