example ios swift uiimageview uiimagepickercontroller
Proyecto Demo

ios - example - uiimagepickercontroller swift 3



Establecer la imagen tomada desde la galerĂ­a al UIImageView (5)

Varios problemas

Si mira los documentos, el método imagePickerController:didFinishPickingImage:editingInfo: se desaprobó en iOS 3.0 .

Es una apuesta justa que ni siquiera se llama. (Usted tiene la línea que configura su controlador de vista cuando el delegado comentó, por lo que el selector de imágenes no llamará a sus métodos de delegado.

En su imagePickerController:didFinishPickingImage:editingInfo: método tiene image2 definido como UIImageView. No lo es, es un UIImage.

Debería image.delegate = self -comentar la línea image.delegate = self .

Debe implementar el método imagePickerController:didFinishPickingMediaWithInfo: lugar de imagePickerController:didFinishPickingImage:editingInfo:

Probablemente también necesite agregar UIImagePickerControllerDelegate a la definición de su clase de controlador de vista para que el compilador sepa que su controlador de vista cumple con el protocolo UIImagePickerControllerDelegate .

El problema al que me enfrento es colocar la imagen que elijo de la galería en el UIImageView (imageChosen).

El código funciona bien sin ningún error, pero la imagen que elegí no está configurada como "imageChosen"

aquí está mi código

class postChoices: UIViewController { @IBOutlet weak var imageChosen: UIImageView! @IBAction func gallery(sender: AnyObject) { var image = UIImagePickerController() //image.delegate = self image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary image.allowsEditing = false self.presentViewController(image, animated: true, completion: nil) } 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. } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image2: UIImageView!, editingInfo: NSDictionary!) { // let selectedImage : UIImageView = image imageChosen.image = image2.image } }


//Complete solution with delegates and image handling import UIKit class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet weak var myImageView: UIImageView! let picker = UIImagePickerController() @IBAction func gallery(sender: AnyObject) { if UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary) != nil { picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary presentViewController(picker, animated: true, completion: nil) } else { noCamera() } } func noCamera(){ let alertVC = UIAlertController(title: "No Camera", message: "Sorry, Gallery is not accessible.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil) alertVC.addAction(okAction) presentViewController(alertVC, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. picker.delegate = self //the required delegate to get a photo back to the app. } //MARK: - Delegates //What to do when the picker returns with a photo func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2 myImageView.contentMode = .ScaleAspectFit //3 myImageView.image = chosenImage //4 dismissViewControllerAnimated(true, completion: nil) //5 } //What to do if the image picker cancels. func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } }

Proyecto Demo


- (void) makeUIImagePickerControllerForCamera:(BOOL)camera { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; [picker setMediaTypes:[NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil]]; [self presentModalViewController: picker animated: YES]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Dismiss the picker [[picker parentViewController] dismissModalViewControllerAnimated:YES]; // Get the image from the result UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"]; myUIImage.image = image; }


Este código me ayudó con veloz 3.0

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { billImageView.contentMode = .scaleAspectFill billImageView.image = pickedImage } self.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true, completion: nil) }


En Swift 3.0 en este código, tiene que seleccionar ambas cámaras de opción y Gallary

import UIKit import Foundation import AVFoundation class HostVC: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{ @IBOutlet weak var imgHostProfile:UIImageView! let captureSession = AVCaptureSession() let stillImageOutput = AVCaptureStillImageOutput() var previewLayer : AVCaptureVideoPreviewLayer? var captureDevice : AVCaptureDevice? @IBAction func btnChangeprofileTapped(_ sender: UIButton) { DispatchQueue.main.async { let alert = UIAlertController(title: "Alert", message: "Choose profile picture from Camera or Gallery", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Take a photo", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in DispatchQueue.main.async { if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized { self.Cemara() } else { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in if granted == true { self.Cemara() } else { self.showalert(strMessage: Validation.kCameraAccess) } }) } } })) alert.addAction(UIAlertAction(title: "Choose from Library", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in DispatchQueue.main.async { let imagepicker = UIImagePickerController() imagepicker.delegate = self imagepicker.sourceType = .photoLibrary self.present(imagepicker, animated: true, completion: nil) } })) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in})) self.present(alert, animated: true, completion: nil) } } func Cemara() { DispatchQueue.main.async { if UIImagePickerController.availableCaptureModes(for: .rear) != nil { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .camera self.present(imagePicker, animated: true, completion: nil) } else { self.noCamera() } } } //====================================================================== // MARK: - Camera Code //====================================================================== func noCamera() { captureSession.sessionPreset = AVCaptureSessionPresetHigh if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] { for device in devices { if (device.hasMediaType(AVMediaTypeVideo)) { if(device.position == AVCaptureDevicePosition.front) { captureDevice = device if captureDevice != nil { print("Capture device found") beginSession() } } } } } } //====================================================================== // MARK: - Camera Capture Start Session Code Here //====================================================================== func beginSession() { do { try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice)) stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG] if captureSession.canAddOutput(stillImageOutput) { captureSession.addOutput(stillImageOutput) } } catch { print("error: /(error.localizedDescription)") } guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else { print("no preview layer") return } self.view.layer.addSublayer(previewLayer) previewLayer.frame = self.view.layer.frame captureSession.startRunning() self.view.addSubview(imgHostProfile) } //====================================================================== // MARK: - Gallary Code //====================================================================== func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let imagedata = info[UIImagePickerControllerOriginalImage] as? UIImage { self.imgHostProfile.image = imagedata print(imagedata) } dismiss(animated: true, completion: nil) }