Last active
November 29, 2017 20:29
-
-
Save jazzedge/d398603e1eec1f559fac08cbb7ea9b14 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment