I'm writing a simple app and I'm not able to show more images from Photo Library in two separate ImageView.
Can anyone help me?
Here's my code:
import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var myImageVie2: UIImageView!
let picker = UIImagePickerController()
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)
}
#IBAction func photoFromLibrary(sender: UIBarButtonItem) {
picker.allowsEditing = false //2
picker.sourceType = .PhotoLibrary //3
picker.modalPresentationStyle = .Popover
presentViewController(picker,animated: true,completion: nil)//4
picker.popoverPresentationController?.barButtonItem = sender
}
//take a picture, check if we have a camera first.
#IBAction func shootPhoto(sender: UIBarButtonItem) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.cameraCaptureMode = .Photo
picker.modalPresentationStyle = .FullScreen
presentViewController(picker,animated: true,completion: nil)
} else {
noCamera()
}
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject])
{
var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
myImageView.contentMode = .ScaleAspectFit
myImageView.image = chosenImage
UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil);
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true,completion: nil)}
}
Related
Hello i am using UIImagePicker to take images but while picking images i want to CROP that image.. How to do that
i am able to pick images from gallery to imageview but while selecting image i need to crop the image.
I have tried below code:
class AddNewEventViewController: UIViewController, UIPickerViewDelegate,UIImagePickerControllerDelegate, UIPickerViewDataSource,UINavigationControllerDelegate {
#IBOutlet weak var imgPick: UIImageView!
var picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
picker.delegate = self
picker.allowsEditing = true
}
#IBAction func addProfileBtnAction(_ sender: Any) {
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheetController.popoverPresentationController?.sourceView = self.contentView
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
}
actionSheetController.addAction(cancelAction)
let takePictureAction: UIAlertAction = UIAlertAction(title: "TakePhoto", style: .default) { action -> Void in
self.openCameraPicker()
}
actionSheetController.addAction(takePictureAction)
let choosePictureAction: UIAlertAction = UIAlertAction(title: "ChooseFromLibrary", style: .default) { action -> Void in
self.openPhotoGallery()
}
actionSheetController.addAction(choosePictureAction)
//Present the
self.present(actionSheetController, animated: true, completion: nil)
}
func openCameraPicker() {
picker.sourceType = UIImagePickerController.SourceType.camera
picker.cameraCaptureMode = .photo
picker.allowsEditing = true
picker.modalPresentationStyle = .fullScreen
present(picker,animated: true,completion: nil)
}
func openPhotoGallery() {
picker.sourceType = .photoLibrary
picker.allowsEditing = true
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let img = info[UIImagePickerController.InfoKey.editedImage] as? UIImage{
imgPick.image = img
}
else if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imgPick.image = image
}
dismiss(animated: true, completion: nil)
}
}
like this i am getting.. no crop
here i am getting images from gallery to imageview but not getting crop.
How to crop the images, please help me with the code.
I check with your code and i found you are missing to set delegate of UIImagePickerController
I try with photoLibrary for now
class ImagePickerViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var imageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.openPhotoGallery()
}
func openPhotoGallery() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let img = info[UIImagePickerController.InfoKey.editedImage] as? UIImage{
imageView.image = img
}
dismiss(animated: true, completion: nil)
}
}
I have a slight problem. I'm trying to make a camera in Swift Xcode, however, I've run into one problem and that is that "ImagePicked.image = image" keeps showing error. I have no idea why it does this. Photo of the interface of the app
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var ImagePicked: UIImageView!
#IBAction func openCamera(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.camera) { //Is the camera an available source type?
let imagePicker = UIImagePickerController() //Declare variable imagePicker
imagePicker.delegate = self
imagePicker.sourceType = .camera;
imagePicker.allowsEditing = false //Tell Image Pickr not to edit camptured photo
self.present(imagePicker, animated: true, completion: nil) //Show the photo to the user
}
func openLibrary(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { //Check if device has access to photo library
let imagePicker = UIImagePickerController() //Set up variable imagePicker
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary; //Set the source type to library
imagePicker.allowsEditing = true //Allow editing, so the user can move and crop their photo
self.present(imagePicker, animated: true, completion: nil) //Show UIImagePickerController to the user
}
}
func saveImage(_ sender: Any) {
let ImageData = ImagePicked.image!.jpegData(compressionQuality: 0.6)
let compressedJPGImage = UIImage(data: ImageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
let alertController = UIAlertController(title: "Complete", message: "Your image has been saved.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default); alertController.addAction(okAction); self.present(alertController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard (info[.originalImage] as? UIImage) != nil else {
fatalError ("Expected a dictionary containtaining an image, but was provided with the following: \(info)")
ImagePicked.image = image //PROBLEM
dismiss(animated: true, completion: nil)
}
}
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
}
Update didFinishPickingMediaWithInfo as below,
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.originalImage] as? UIImage else { return }
ImagePicked.image = image
picker.dismiss(animated: true, completion: nil)
}
As #rmaddy commented, you should rearrange the methods as below,
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var ImagePicked: UIImageView!
#IBAction func openCamera(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.camera) { //Is the camera an available source type?
let imagePicker = UIImagePickerController() //Declare variable imagePicker
imagePicker.delegate = self
imagePicker.sourceType = .camera;
imagePicker.allowsEditing = false //Tell Image Pickr not to edit camptured photo
self.present(imagePicker, animated: true, completion: nil) //Show the photo to the user
}
}
func openLibrary(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { //Check if device has access to photo library
let imagePicker = UIImagePickerController() //Set up variable imagePicker
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary; //Set the source type to library
imagePicker.allowsEditing = true //Allow editing, so the user can move and crop their photo
self.present(imagePicker, animated: true, completion: nil) //Show UIImagePickerController to the user
}
}
func saveImage(_ sender: Any) {
let ImageData = ImagePicked.image!.jpegData(compressionQuality: 0.6)
let compressedJPGImage = UIImage(data: ImageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
let alertController = UIAlertController(title: "Complete", message: "Your image has been saved.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default); alertController.addAction(okAction); self.present(alertController, animated: true, completion: nil)
}
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
I have an app lets user add his image. For this I use UIImagePicker.
Please take a look at the following function:
It opens a view as a popup when image is tapped.
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let userDetails:Dictionary = (UserDefaults.standard.value(forKey: "myUserDetails") as? [String:Any])!
let UserID:Int = userDetails["UserID"] as! Int
let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "imager") as! imagerVC
popOverVC.UserID = UserID
self.addChildViewController(popOverVC)
popOverVC.view.frame = self.view.frame
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)
popOverVC.callback = { image in
// do something with the image
self.profile_image.image = image
if let data = UIImagePNGRepresentation(image) {
//save profile image as NewUserID
UserDefaults.standard.set(data, forKey: String(UserID))
UserDefaults.standard.synchronize()
}
}
}
This is the View code that activates the camera and this view is opened as popOverVC from the code above.
import UIKit
class imagerVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var UserID:Int = 0
#IBOutlet weak var myImageView: UIImageView!
var callback : ((UIImage) -> ())?
#IBOutlet weak var btn_end: UIButton!
#IBOutlet weak var from_camera: UIBarButtonItem!
#IBOutlet weak var from_gallery: UIBarButtonItem!
#IBAction func btn_end_pressed(_ sender: UIButton) {
self.view.removeFromSuperview()
}
#IBAction func btn_closer(_ sender: UIButton) {
self.view.removeFromSuperview()
}
#IBAction func photofromLibrary(_ sender: UIBarButtonItem) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.modalPresentationStyle = .popover
present(picker, animated: true, completion: nil)
picker.popoverPresentationController?.barButtonItem = sender
}
#IBAction func shootPhoto(_ sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
UserDefaults.standard.set(true, forKey: "is_selfie")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.picker.allowsEditing = false
self.picker.sourceType = UIImagePickerControllerSourceType.camera
self.picker.cameraCaptureMode = .photo
self.picker.modalPresentationStyle = .fullScreen
self.present(self.picker,animated: true,completion: nil)
}
} else {
noCamera()
}
}
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Delegates
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
myImageView.contentMode = .scaleAspectFit //3
myImageView.image = chosenImage //4
myImageView.layer.borderWidth = 1
myImageView.layer.masksToBounds = false
myImageView.layer.borderColor = UIColor.black.cgColor
myImageView.layer.cornerRadius = myImageView.frame.height/4
myImageView.clipsToBounds = true
callback?(chosenImage)
dismiss(animated:true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
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)
present(
alertVC,
animated: true,
completion: nil)
}
}
I have two problems. Maybe they are related.
The main problem is that after the camera view loads and the picture is taken, When I press the button Use photo, the camera does not get dismissed at once and there is a lag of about a minute till the camera view is dismissed. The callback function by the way get triggered as soon "use photo" button is pressed.
I am not sure if this is connected but I get the following warning:
Instance method 'imagePickerController(_:didFinishPickingMediaWithInfo:)' nearly matches requirement yet when i let Xcode autocorrect me the camera functionality ceases to function.
I tried wrapping the line
dismiss(animated:true, completion: nil)
in DispatchQueue.main.async to make it run on main thread but that did not work
Not sure why but lag does not occur in physical IPad, only iPhone devices
Any help rendered is greatly appreciated
this is as expected behaviour on simulators. It should not lag on device and as you said its working on device then its cool. !!!
Im trying to learn how to access and use the camera on IOS devices, trufully i cant find all that much info on it, at least not thats up to date or useful to learn at a beginner level.
Regardless, I've tried the below code but nothing happens when I click the button to open the camera it just freezes and does nothing, am i missing something or have i done something wrong?
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var myImg: UIImageView!
var newMedia: Bool!
#IBAction func cameraRoll(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
self.dismiss(animated: true, completion: nil)
if mediaType.isEqual(to: kUTTypeImage as String){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
myImg.image = image
if (newMedia == true) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(ViewController.image(image:didFinishsavingWithError:contextInfo:)), nil)
} else if mediaType.isEqual(to: kUTTypeMovie as String){
//vid support
}
}
}
func image(image: UIImage, didFinishsavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer){
if error != nil {
let alert = UIAlertController(title: "Save Failed", message: "Failed to save image", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func takePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
Would please review my code, I do not have any errors, but when I open my view controller, the camera doesn't start there is only a black screen, even the buttons do not appear.
import UIKit
import AVFoundation
class CameraViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
let picker = UIImagePickerController()
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var cameraView: UIView!
#IBAction func photoLibrary(_ sender: UIBarButtonItem) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.modalPresentationStyle = .popover
present(picker, animated: true, completion: nil)
picker.popoverPresentationController?.barButtonItem = sender
}
#IBAction func shootPhoto(_ sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,animated: true,completion: nil)
} else {
noCamera()
}
}
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)
present(
alertVC,
animated: true,
completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
//MARK: - Delegates
private func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
{
var chosenImage = UIImage()
chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
myImageView.contentMode = .scaleAspectFit //3
myImageView.image = chosenImage //4
dismiss(animated:true, completion: nil) //5
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
I only get completely black screen, even no hints from Swift. I do not know what to do now.
This happens when you have not set an initial viewcontroller. Please make sure the viewcontroller you want to load first is set as initial viewcontroller in your storyboard.