imageview not updating after an image is picked - ios

I have the following problem. I use a imagepickerdelegate to choose a image from my photo library and to apply this in the UIImageView. The problem is that it won't update the UIImageview with my chosen image.
I inherit both
UIImagePickerControllerDelegate, UINavigationControllerDelegate
This is my image view.
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 99 / 2
imageView.layer.masksToBounds = true
imageView.image = UIImage(named: "profileimg")
imageView.contentMode = .scaleToFill
return imageView
}()
Then the functions to handle choosing and setting the image inside the UIImageView look like these.
func addProfilePhoto() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedPickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImageFromPicker = editedPickedImage
} else if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
selectedImageFromPicker = pickedImage
}
if let selectedImage = selectedImageFromPicker {
print("set image")
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
self.profileImageView.image = selectedImage
self.dismiss(animated: true, completion: nil)
}
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
My log gives the following messages when I tap on the UIImageView:
[Generic] Creating an image format with an unknown type is an error
And when I choose an image it confirms that there is an image but it won't show.
set image
Any idea what I am doing wrong?

I checked your code, seem you have not code for display profileImageView on screen. So, you do not see it. Example:
profileImageView.frame = ........
self.view.addSubview(profileImageView)

Related

image picker controller not able to change the default crop square size after clicking image from iphone

image showing the imagepickercontroller
As shown in this figure, that square position is not changing or resizing when i take picture from camera but it is working from gallery. Please help to how to change the position of crop square to go to required part of image.
the code used is given below
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
print(image.size)
let croppedImage = info[UIImagePickerControllerEditedImage] as? UIImage
print(croppedImage ?? "")
let cropRect = (info[UIImagePickerControllerCropRect]! as AnyObject).cgRectValue
print(cropRect?.size ?? "")
let _ = UIImage.cropImage(image: image, toRect: CGRect.init(x: 0, y: 0, w: self.imgProfile.bounds.width, h: self.imgProfile.bounds.width))
print(image.size)
self.imgProfile.image = croppedImage
profileImgUpdated = true
}
self.dismiss(animated: true, completion: nil)
}
func openCamera(){
self.imagePicker.sourceType = .camera
self.imagePicker.allowsEditing = true
self.imagePicker.delegate = self
self.present(imagePicker, animated: true)
}
func openPhotoLibrary() {
self.imagePicker.sourceType = .photoLibrary
self.imagePicker.allowsEditing = true
self.imagePicker.delegate = self
self.present(imagePicker, animated: true)
}
In Swift 4.2 didFinishPickingMediaWithInfo info: [String : Any] is depricated, try with,
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.imgProfile.image = editedImage
} else if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imgProfile.image = image
}
self.dismiss(animated: true, completion: nil)
}
To enable editing,
let picker = UIImagePickerController()
picker.allowsEditing = true

Set background of another view in swift

I'd like to let the user chose a background for the main view of the app.
I'd like to know how I can do that for another view, even if the app is killed.
I thought about saving the path of the image in Userdefaults and then get it from the main view, but I'm not able to set the background from an asset URL. Is there a way to do this ? Or a better way maybe ?
Here is what I've done so far:
#IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()
#IBAction func background(_ sender: Any) {
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .savedPhotosAlbum
imagePicker.modalPresentationStyle = .overCurrentContext
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imageView.contentMode = .scaleAspectFit
let imageUrl = info[UIImagePickerControllerReferenceURL] as! URL
UserDefaults.standard.set(imageUrl, forKey: "background")
imageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.imagePicker = UIImagePickerController()
dismiss(animated: true, completion: nil)
}
How about loading URL from defaults in viewDidLoad() and then call setImageFromURL? Of course you have to set the image to your ImageView
func setImageFromURl(stringImageUrl url: String){
if let url = NSURL(string: url) {
if let data = NSData(contentsOf: url as URL) {
self.image = UIImage(data: data as Data)
}
}
}

How to enable the edit feature of "Photos" in my app? [Swift 3]

Issue:
Even if this is set to true:
imagePicker.allowsEditing = true
It only shows the crop feature, which works for iPhone-sized devices but not for iPad sized devices (cropping won't work properly, it returns the wrong part of the picture).
How could I enable the edit functionality of the "Photos", so that the user may instead use this crop feature?
Did finish method:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
isImageChanged = true
if UIDevice.current.userInterfaceIdiom == .pad {
//Code for iPad problem
pictureBox.image = image
}else{
pictureBox.contentMode = .scaleAspectFit
pictureBox.image = image
}
self.dismiss(animated: true, completion: nil)
}
Calling ImagePickerController
let alertAction2 = UIAlertAction(title: "Library", style:UIAlertActionStyle.default){(UIAlertAction)-> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
if UIDevice.current.userInterfaceIdiom == .pad {
imagePicker.allowsEditing = true
} else if UIDevice.current.userInterfaceIdiom == .phone {
imagePicker.allowsEditing = true
}
self.present(imagePicker, animated: true, completion: nil)
}
}
I had the same problem and there is a simple solution. When using the imagePickerController on iPad's you have to present it as a popover in order for editing to work properly. Source
Below are some images to illustrate that editing works.
Next, we have the issue of the popOver on an iPhone. The popover cannot display on an iPhone so it will just display the normal picker which takes up the whole screen. Note you might also want to check if you have access to the photo library or camera too. (Code for that is in the link provided above.)
#IBAction func selectImagePressed(_ sender: Any) {
// check if we can access the library first? If no we need to ask again
picker.allowsEditing = true
picker.sourceType = .photoLibrary // can be camera or library
picker.modalPresentationStyle = .popover
picker.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate
picker.popoverPresentationController?.sourceView = view
let screenSize = UIScreen.main.bounds
let xLocation = (screenSize.width / 100) * 15
let yLocation = (screenSize.height / 2)
picker.popoverPresentationController?.sourceRect = CGRect(x: xLocation, y: yLocation, width: 0, height: 0)
present(picker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
// Use editedImage Here
self.imageView.image = editedImage
nextButton.isHidden = false
}
else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Use originalImage Here
self.imageView.image = originalImage
nextButton.isHidden = false
}
else {
if let vc = UIApplication.topViewController() {
Helper.showAlertMessage(vc: vc, title: "Image Error", message: "An error occured during image selection")
}
}
picker.dismiss(animated: true)
}

iOS, Swift, UIImagePicker allows editing crop tool removes transparency. Is there fix?

When I get PNG image with transparent background from UIImagePicker it inserts the image with the transparent background just fine as below:
when I set:
imagePicker.allowsEditing = true
it allows me to crop as expected in the view provided by UIImagePicker
but then when I press 'Choose' it returns the image with black instead of a transparent background as below:
The only change between the two results is setting
imagePicker.allowsEditing = true
and cropping the image in the app.
Is there a way to keep transparency or at least change the black to white when cropping?
I have searched the internet and no mention of this that I can see.
Code:
func showImagePicker() {
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
compImageView?.contentMode = .scaleAspectFit
compImageView?.backgroundColor = UIColor.clear
compImageView?.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
By default UIImagePickerController removes the alpha channels in the edited image. To get that transparency you have to edit image yourself. Implement delegate method like this:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let cropRect = info[UIImagePickerControllerCropRect] as? CGRect {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let imageRef: CGImage = image.cgImage!.cropping(to: cropRect)!
let image1: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
imageView.image = image1
picker.dismiss(animated: true, completion: nil)
}
}
}
Please try this code.
import MobileCoreServices //importing for mediaType kUTTypeImage
func showImagePicker() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
let mediaTypes: Array<AnyObject> = [kUTTypeImage]
imagePicker.mediaTypes = mediaTypes as! [String]
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if picker.sourceType == UIImagePickerControllerSourceType.photoLibrary {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
dismiss(animated: true, completion: nil)
compImageView?.image = image
}
}
}

UIImageView won't display chosen image from UIImagePicker

My imageView doesn't display the picture I choose with the UIImagePicker.
Here's all the code for it:
#IBAction func addImage(_ sender: Any) {
if !didShowCamera {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
} else {
imagePicker.sourceType = .photoLibrary
}
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
print(image)
self.jobImage.image = takenImage
self.takenImage = image
didShowCamera = true
self.dismiss(animated: true, completion: nil)
}
Any ideas how to solve it?
Use dispatch main queue
DispatchQueue.main.async {
self.jobImage.image = takenImage
self.takenImage = image
}
I guess the takenImage is nil while assigning to image view, you need to assign image to takenImage before setting to the image view. please update the method like,
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
print(image)
self.takenImage = image
self.jobImage.image = takenImage
didShowCamera = true
self.dismiss(animated: true, completion: nil)
}
Replace
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
with
let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
And check whether you have add privacy-photo library access in info.plist.
See detailed at [https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html#//apple_ref/doc/uid/TP40015214-CH6-SW1][1]

Resources