Swift 3 - Cannot override 'imagePickerController' - xcode

My code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.image = image
self.imageStatusLabel.text = "There is a picture"
self.imageStatusLabel.textColor = UIColor.blue()
picker.dismiss(animated: true, completion: nil)
}
And this is the error:
Cannot override 'imagePickerController' which has been marked unavailable: APIs deprecated as of iOS 7 and earlier are unavailable in Swift
Well, I've tried to use the newer function:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// But no image in the parameters
}
But then, there is no image in the parameters and I can get the image.
What should I do?

You have to use the info parameter and make a cast to UIImage. Don't forget that you have to put a "Privacy - Photo Library Usage Description" and a "Privacy - Camera Usage Description" in the info.plist file and fill the values with a string explaining the reason for request the access to photo library and camera.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
pictureImageView.contentMode = .scaleToFill
pictureImageView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}

To use imagePickerController in Swift3 you need add a row with key: Privacy - Photo Library Usage Description and value is a string (e.g: "Access to your photos") to Info.plist file and let's try below:
class YourController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePickerButton: UIButton = {
let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
btn.setTitle("Choose a Photo", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.backgroundColor = .blue
btn.addTarget(self, action: #selector(handlePickerDidTap), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imagePickerButton)
}
func handlePickerDidTap() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("photo is selected")
// do some thing here
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
Hope it help!

You get the image from the passed info dictionary, see the keys in the documentation
You probably want either
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
or
let image = info[UIImagePickerControllerEditedImage] as? UIImage

import UIKit
import Photos
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBAction func selectPhotoLibrary(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = .camera
} else{
print("Kamera desteklenmiyor.")
}
present(picker, animated: true, completion:nil)
}
#IBAction func selectPhotoCamera(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
guard let imageData = UIImageJPEGRepresentation(image, 0.8) else { return }
self.imageView.image = image
print(imageData)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Read more for usage detail --> https://medium.com/#yakupad/swift-uiimagepickercontroller-kullanımı-91771ed4c1d6

Related

Using Xcode and getting error "Cannot assign to property: 'image' is a method

I'm new to coding and would really appreciate some help on this. I've searched everywhere for a fix to my issue, but can't find one that makes sense to me. Here's my code (error location noted). Thanks in advance!
import UIKit
import Firebase
class UserVC: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: UIButton!
#IBOutlet weak var completeSignUpBtn: UIButton!
var userUid: String!
var emailField: String!
var passwordField: String!
var imagePicker: UIImagePickerController!
var imageSelected = false
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
userImagePicker.image = image **//error here**
imageSelected = true
}else {
print("image wasn't selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
#IBAction func completeAccount (_ sender: Any){
Auth.auth().createUser(withEmail: emailField, password: passwordField, completion:
{(user, error) in
if error != nil {
print(error)
}else{
if let user = user {
self.userUid = user.uid
}
}
})
}
#IBAction func selectedImagePicker(_ sender: Any){
present (imagePicker, animated: true, completion: nil)
}
#IBAction func cancel (_ sender: AnyObject){
dismiss (animated: true, completion: nil)
}
}
You cannot directly assign image to UIButton. Button has different method to set images. Here is swift 3 sample code to set button image.
let playButton = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
So try this
userImagePicker.setImage(image,for:.normal)

Swift Error: EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I'm trying to make this posting app similar to instagram but I am getting stuck on a issue once i press my compose button. This button is suppose to post the image but instead its crashing. I'm having an error after I try to upload a caption\image with my app here:
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
It is giving me this error:EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Please help!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
let file: PFFile = PFFile(data: imageData)!
let fileCaption: String = self.captionTextView.text
let photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["data"] = localDate
//Get bytes size of image
/* var imageSize = Float(imageData!.length)
//Transform into Megabytes
imageSize = imageSize/(1024*1024)
print("Image size is \(imageSize)Mb")
*/
do{
try photoToUpload.save()
} catch _ {
}
print("Successfully Posted.")
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("postController")
self.presentViewController(vc! as UIViewController, animated: true, completion: nil)
}
It seems that you are unwraping an optional value without actualy checking if it is nil.
Probably the issue is from let file: PFFile = PFFile(data: imageData)!. You must check for nil before you unwrap a variable.

how do to get an image from one viewController to the next like a global

I have just a camera on my CameraController. I want the picture from my CameraContoller to go to my ComposeViewController inside of the image View in the ComposeViewController. so basically I need it so the the picture taken transfers to the other view controller once taken. There are 2 separate view controllers below in the code.
Code:
import UIKit
import AVFoundation
class CameraController : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
#IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer)
captureSession?.startRunning()
}
}
}
#IBOutlet var tempImageView: UIImageView!
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
}
})
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
tempImageView.hidden = true
didTakePhoto = false
}
else{
captureSession?.startRunning()
didTakePhoto = true
didPressTakePhoto()
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
didPressTakeAnother()
}
}
//-----Below is my Next View Controller where i want the image from the above view controller to show up--------------------------------------- --------------------------------------------------------------------------- --------------
class ComposeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
let tap = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "GotoProfile")
swipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipe)
tap.numberOfTapsRequired = 2
tap.addTarget(self, action: "GoBack")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func CaptonField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.length + range.location > count(captionTextView.text){
return false
}
let NewLength = count(captionTextView.text) + count(string) - range.length
return NewLength <= 35
}
#IBAction func chooseImageFromCamera() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker,animated: true, completion:nil)
}
func GotoProfile(){
self.performSegueWithIdentifier("NewCameraViewFromComposeSegue", sender: nil)
}
func GoBack(){
self.performSegueWithIdentifier("GoBackFromCamerasegue", sender: nil)
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded)
let file: PFFile = PFFile(data: imageData)
let fileCaption: String = self.captionTextView.text
var photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["date"] = localDate
photoToUpload.save()
println("Successfully Posted.")
let vc: AnyObject? = self.storyboard?.instantiateViewControllerWithIdentifier("NavigationController")
self.presentViewController(vc as! UIViewController, animated: true, completion: nil)
}
}
Are you using a segue to get from the first to the second ViewController ?
If so you can access the second VC in in your first VC in the prepareForSegue function :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ComposeVCIdentifier" {
let composeViewController = segue.destinationViewController as! ComposeViewController
composeViewController.someVariable = myPicture
}
}

How do I add an image filter only in the touch radius in swift

I am new to swift and I have an app which allows the user to get a picture from their camera roll and display it in an imageview. I have found plenty of tutorials on how to add filters, but how do I isolate this to a touch radius, not the entire image?
import UIKit
import AVFoundation
import Social
import MobileCoreServices
import MessageUI
import iAd
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate, UITextFieldDelegate, UITextViewDelegate {
#IBOutlet var imageView: UIImageView!
let picker = UIImagePickerController()
var cameraUI: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func filter(sender: UIButton) {
let myPicture = imageView.image
let filter = CIFilter(name: "CIPhotoEffectMono")
filter.setValue(CIImage(image: myPicture), forKey: kCIInputImageKey)
let newImage = UIImage(CIImage: filter.outputImage)
imageView.image = newImage
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let myPicture = imageView.image
for obj in touches {
let touch = obj as! UITouch
let location = touch.locationInView(self.view)
}
}
#IBAction func getImageButton(sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
{
cameraUI = UIImagePickerController()
cameraUI.delegate = self
cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
cameraUI.mediaTypes = [kUTTypeImage]
cameraUI.allowsEditing = false
self.presentViewController(cameraUI, animated: true, completion: nil)
}
else
{
let alertVC = UIAlertController(title: "Error", message: "Cannot open camera roll.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
alertVC.addAction(okAction)
presentViewController(alertVC, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
imageView.contentMode = .ScaleAspectFit //3
imageView.image = chosenImage //4
dismissViewControllerAnimated(true, completion: nil) //5
}
func noCamera(){
let alertVC = UIAlertController(title: "No Camera", message: "Sorry, this device has no camera", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
alertVC.addAction(okAction)
presentViewController(alertVC, animated: true, completion: nil)
}
func savedImageAlert()
{
var alert:UIAlertView = UIAlertView()
alert.title = "Saved!"
alert.message = "Your picture was saved"
alert.delegate = self
alert.addButtonWithTitle("Ok")
alert.show()
}
}

Accessing picture library in an ActionSheet style

I'm trying to create a profilePic in a Sign Up View Controller. The profilePic is of type UIImageView. I want to be able to tap it so it instantly pulls up a photo library in an ActionSheet Style. And to also have one of the image box a button to access the camera. Is this possible?
import UIKit
class SignUpViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// PROFILE PICTURE
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
}
}
Try this code below :
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
showActionSheet()
}
}
func camera()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Its working on my side..hope will do the some for you !
I recently published a GitHub repository to handle this type of Action Sheet.
You can download this class from here : MSActionSheet
and simply write :
EDIT :
● Now supporting iPad
MSActionSheet(viewController: self, sourceView: sender).showFullActionSheet {
sender.setImage($0, for: .normal)
}
MSActionSheet : is the best library for set user's profile picture.
I used this library but it's not supported in iPad so i
customise for some functions for support to iPad and Display with
popOverController.
Below the step of customisation.
Replace function with showFullActionSheet
func showFullActionSheet(on vc : UIViewController, over btn : UIButton,handler : #escaping (_ : UIImage?) -> Void) {
let sheet = create().addLibrary().addFrontCamera().addRearCamera().addCancelButton()
sheet.show(on: vc,over: btn){ (image : UIImage?) in
handler(image)
}
}
Add code before vc.present(MSActionSheet.sheet!, animated: true, completion: nil) in function show
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
if let presenter = MSActionSheet.sheet?.popoverPresentationController {
presenter.sourceView = btn
presenter.sourceRect = btn.bounds
}
}
Add below code before clientVC?.present(picker, animated: true, completion: nil) in function handler
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
picker.modalPresentationStyle = .popover
if let presenter = picker.popoverPresentationController {
presenter.sourceView = sourceBtn
presenter.sourceRect = sourceBtn!.bounds
}
}
How to use
let msActionSheet = MSActionSheet.instance
msActionSheet.showFullActionSheet(on: self,over: btn){ (image) in
btn.setImage(image, for: .normal)
}
msActionSheet.tintColor(color: Constants.kColorBluish)
Swift 3x:
class yourClassName:UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBAction func yourButtonName(_ sender: UIButton) {
let pickerView = UIImagePickerController()
pickerView.delegate = self
pickerView.allowsEditing = true
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: nil, preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel") //Cancel
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton: UIAlertAction = UIAlertAction(title: "Take Photo", style: .default) { action -> Void in
print("Take Photo") //Will open Camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
pickerView.sourceType = .camera
self.present(pickerView, animated: true, completion: { _ in })
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton: UIAlertAction = UIAlertAction(title: "Camera Roll", style: .default) { action -> Void in
print("Camera Roll") //Will open Gallery
pickerView.sourceType = .photoLibrary
self.present(pickerView, animated: true, completion: { _ in })
}
actionSheetControllerIOS8.addAction(deleteActionButton)
let deleteActionButton2: UIAlertAction = UIAlertAction(title: "Import from Facebook", style: .default) { action -> Void in
print("Import from Facebook")
}
actionSheetControllerIOS8.addAction(deleteActionButton2)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//print(info)
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
//print(pickedImage)
yourImageView.contentMode = .scaleAspectFit
yourImageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
}

Resources