Unresolved identifier error 'email' - ios

This is related to a previous question that was solved (See here: Sharing variables). I saw nothing that addresses what to do if your variable still isn't being recognized but your code to pass the variable appears solid.
I'm getting an unresolved identifier error 'email' when attempting to utilize a user's email address as part of a file path to upload an image to Firebase Storage. Code is here:
import UIKit
import Firebase
import MobileCoreServices
import FirebaseStorage
class ThirdViewController: UIViewController {
#IBOutlet weak var uploadButton: UIButton!
#IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"Book Funnel")!)
// Do any additional setup after loading the view.
}
#IBAction func uploadButtonWasPressed(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
func uploadImageToFirebaseStorage(data: NSData) {
let storageRef = FIRStorage.storage().reference(withPath: email/"/image.jpg")
let uploadMetadata = FIRStorageMetadata()
uploadMetadata.contentType = "image/jpeg"
let uploadTask = storageRef.put(data as Data, metadata: uploadMetadata) { (metadata, error) in
_ = metadata?.downloadURL
if (error != nil) {
print("I recieved an error! \(error?.localizedDescription)")
} else {
print ("Upload complete! Here's some metadata! \(metadata)")
}
let alert = UIAlertController(title: "Success!", message: "Image uploaded", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
uploadTask.observe(.progress) { [weak self] (snapshot) in
guard let strongSelf = self else { return }
guard let progress = snapshot.progress else { return }
strongSelf.progressView.progress = Float(progress.fractionCompleted)
}
}
var toPass: String!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension ThirdViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let mediaType: String = info[UIImagePickerControllerMediaType] as? String else {
dismiss(animated: true, completion: nil)
return
}
if mediaType == (kUTTypeImage as String) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage, let imageData = UIImageJPEGRepresentation(originalImage, 0.8) {
uploadImageToFirebaseStorage(data: imageData as NSData)
}
} else {
print("Please select an image")
}
dismiss(animated: true, completion: nil)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
if let fourthVC = segue.destination as? FourthViewController {
fourthVC.toPass = "email"
}
}
}
}
}

Related

My segue is not executed after taking a pic

I'm developing an app which uses a camera and then the photo is supposed to be sent to another ViewController, but i'm not sure if it maybe the segue is not be able to there or that it is just be executed, but when I confirm the photo my app crashed and no errors are showed on my log.
This is the camera View controller
import UIKit
import AVFoundation
class ViewController: UIViewController ,
UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var img = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func photo(_ sender: Any) {
checkCameraPermissions()
}
private func checkCameraPermissions() {
let status = AVCaptureDevice.authorizationStatus(for: .video)
switch status {
case .authorized:
print("1")
presentPicker()
case .notDetermined:
print("2")
askPermision()
case .denied:
print("3")
// user denied access
self.permissionDenied()
case .restricted:
print("Error restricted")
}
}
private func presentPicker() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
img.image = pickedImage
}
performSegue(withIdentifier: "captured", sender: nil)
}
private func askPermision(){
AVCaptureDevice.requestAccess(for: AVMediaType.video) {granted in
if granted {
self.presentPicker()
} else {
print("Denied")
}
}
}
private func permissionDenied() {
let alert = UIAlertController(title: "Access to camera is denied", message: "You have denied the access to the camera. Would you like to able it?", preferredStyle: .alert)
let actionOK = UIAlertAction(title: "Ok", style: .default) { (UIAlertAction) in
self.askPermision()
}
let cancel = UIAlertAction(title: "Cancel", style: .default) { (action) in
print("Cancel")
}
alert.addAction(actionOK)
alert.addAction(cancel)
present(alert, animated : true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "captured"){
let vc = segue.destination as! ImageReportedVC
vc.imgAux = img.image!
}
}
}
And then, this is the 2nd VC which doesn't appear. I believe the segue shouldn't be done there or something, but if you put it in another part of the code, it is executed before taking the photo.
import UIKit
class ImageReportedVC: UIViewController {
var imgAux = UIImage()
#IBOutlet weak var imgReported: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imgReported.image = imgAux
// Do any additional setup after loading the view.
}
}
Thanks
You need to dismiss the picker
picker.dismiss(animated:true) {
self.performSegue(withIdentifier: "captured", sender: nil)
}

UIImagePickerController what is the right approach to avoid error Code=13 "query cancelled"

I'm implementing a photopicker in my project and it works or not, with the same code, depending the way I implement it. In my first approach I was using a custom UIAlertAction class and doing all the stuff in there, to have my main controller lighter, but the picker delegate was never called, instead it prints an error message in the console ([discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}) and I would like to discuss if the way I were implementing the picker was right or wrong and why? Or if it's a bug from apple. I've been googling for a while and checking all the related questions in stack overflow, and anything has worked for me except to put the picker code in my main controller.
Here is the code of my main controller, when it was not calling the delegate:
First approach that give me error and don't call delegates
import UIKit
import MobileCoreServices
import Photos
class ViewController: UIViewController {
#IBOutlet weak var lblMain: UILabel!
#IBOutlet weak var buttonsBottom: NSLayoutConstraint!
#IBOutlet weak var imgFromUser: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
hideButtons()
}
override func viewDidAppear(_ animated: Bool) {
showButtons()
checkPermission()
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized: print("Access is granted by user")
case .notDetermined: PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized { print("success") }
})
case .restricted: print("User do not have access to photo album.")
case .denied: print("User has denied the permission.")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func hideButtons()
{
buttonsBottom.constant += self.view.frame.size.height * 0.15
}
func showButtons(){
UIView.animate(withDuration: 0.5) {
}
UIView.animate(withDuration: 0.5, animations: {
self.buttonsBottom.constant = 0
self.view.layoutIfNeeded()
}) { (completed) in
self.lblMain.text = firstController.lblMain
}
}
#IBAction func addImagePressed(_ sender: Any) {
let alertViewController : AlertAction = AlertAction.init(controller: self, type: .photoGallery)
self.present((alertViewController.setType(alert: .photoGallery)), animated: true, completion: nil)
}
}
And this is my custom AlertAction class, it implements the picker & navigation delegate, creates the UIImagePickerController, sets the delegate to it, creates the alert action and set it to present the main view controller, adds it to a UIAlertController and gets returned to the main view controller which present it:
import UIKit
import Photos
class AlertAction: UIAlertAction {
var destinationController : ViewController?
var imagePicker = UIImagePickerController()
convenience init(controller : ViewController, type : type) {
self.init()
destinationController = controller
//Init picker
imagePicker.delegate = self
imagePicker.sourceType = type == .photoGallery ? UIImagePickerControllerSourceType.photoLibrary : UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
}
enum type {
case camera
case photoGallery
}
var alertType : type = .camera
func setType(alert : type) -> UIAlertController {
alertType = alert
return alertType == .camera ? newAlert() : newAlert()
}
func newAlert() -> UIAlertController{
//set alert text
let alertText = alertType == .camera ? AlertText.typeCamera : AlertText.typeGalery
let myAlert = UIAlertController(title: AlertText.title, message: "", preferredStyle: .actionSheet)
if alertType == .camera {
myAlert.addAction(getCameraAction(alertText: alertText))
return myAlert
}
else{
myAlert.addAction(getGalleryAction(alertText: alertText))
return myAlert
}
}
func getCameraAction(alertText : String) -> UIAlertAction{
let cameraAction = UIAlertAction(title : alertText, style : .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.destinationController!.present(self.imagePicker, animated: true, completion: nil)
}
}
return cameraAction
}
func getGalleryAction(alertText : String) -> UIAlertAction{
let photoLibraryAction = UIAlertAction(title: alertText, style: .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
self.destinationController!.present(self.imagePicker, animated: true, completion: nil)
}
}
return photoLibraryAction
}
}
extension AlertAction : UIImagePickerControllerDelegate {
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kCIAttributeTypeImage as String){
destinationController!.imgFromUser.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
destinationController!.dismiss(animated: true, completion: nil)
}
#objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
destinationController!.dismiss(animated: true, completion: nil)
}
}
extension AlertAction : UINavigationControllerDelegate {
}
After reading a while, I've been trying all the posible solutions in this custom class but nothing worked.
Then I tried to implement a picker creation method in my main view controller and it worked.
So my question is very simple, why the delegate methods get called only if I do all the coding stuff in the main view controller but don't work in a custom class?
Here is the code that I'm currently using and works:
Second approach that works, all the code in the same ViewController
import UIKit
import MobileCoreServices
import Photos
class ViewController: UIViewController {
#IBOutlet weak var lblMain: UILabel!
#IBOutlet weak var buttonsBottom: NSLayoutConstraint!
#IBOutlet weak var imgFromUser: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
hideButtons()
}
override func viewDidAppear(_ animated: Bool) {
showButtons()
checkPermission()
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized: print("Access is granted by user")
case .notDetermined: PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized { print("success") }
})
case .restricted: print("User do not have access to photo album.")
case .denied: print("User has denied the permission.")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func hideButtons()
{
buttonsBottom.constant += self.view.frame.size.height * 0.15
}
func showButtons(){
UIView.animate(withDuration: 0.5) {
}
UIView.animate(withDuration: 0.5, animations: {
self.buttonsBottom.constant = 0
self.view.layoutIfNeeded()
}) { (completed) in
self.lblMain.text = firstController.lblMain
}
}
#IBAction func addImagePressed(_ sender: Any) {
self.present(addPicker(), animated: true, completion: nil)
}
//MARK: Picker methods
func addPicker()->UIAlertController{
let alertText = AlertText.typeGalery
let myAlert = UIAlertController(title: AlertText.title, message: "", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title : alertText, style : .default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
myAlert.addAction(cameraAction)
return myAlert
}
}
extension ViewController : UIImagePickerControllerDelegate {
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.imgFromUser.image = image
}
if mediaType.isEqual(to: kCIAttributeTypeImage as String){
self.imgFromUser.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
self.dismiss(animated: true, completion: nil)
}
#objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
}
extension ViewController : UINavigationControllerDelegate {
}
Update: the error [discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled} still appears in my second implementation, but only when I remove #objc before the picker delegate method and environement varibable OS_ACTIVITY_MODE = disable is not set, but the code still works anda the delegates are called correctly (in the second implementation) so basically this error is not related with the code functionality and don't describe anything useful

How to Crop iPhone Image in Swift 3 App

I am currently in the process of creating a camera app, however when someone takes a picture and it goes to the the crop screen, it doesn't actually fit it to that specific size. How can I change my code to make it only spit out a 800x800 image?
import UIKit
import Firebase
class CameraControllerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var postBtn: UIButton!
#IBOutlet weak var pickedimage: UIImageView!
#IBOutlet weak var libBtn: UIButton!
#IBOutlet weak var camBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func camerabuttonaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated:true, completion: nil)
}
}
#IBAction func photolibraryaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveaction(_ sender: Any) {
let imageData = UIImageJPEGRepresentation(pickedimage.image!, 0.6)
let compressedJPEGImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPEGImage!, nil, nil, nil)
saveNotice()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]! ) {
pickedimage.image = image
camBtn.isHidden = true
libBtn.isHidden = true
postBtn.isHidden = false
self.dismiss(animated: true, completion: nil);
}
func saveNotice() {
AppDelegate.instance().showActivityIndicator()
//let alertController = UIAlertController(title: "Image Saved", message: "Your picture was saved.", preferredStyle: .alert)
//let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
//alertController.addAction(defaultAction)
//present(alertController, animated: true, completion: nil)
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://new-glaance.appspot.com")
let key = ref.child("posts").childByAutoId().key
let imageRef = storage.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.pickedimage.image!, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata,error) in
if error != nil {
print(error!.localizedDescription)
AppDelegate.instance().dismissActivityIndicator()
return
}
imageRef.downloadURL(completion: { (url, error) in
if let url = url {
let feed = ["userID": uid,
"pathToImage": url.absoluteString,
"likes":0,
"author": Auth.auth().currentUser!.displayName!,
"postID": key] as [String: Any]
let postFeed = ["\(key)":feed]
ref.child("posts").updateChildValues(postFeed)
AppDelegate.instance().dismissActivityIndicator()
}
})
}
uploadTask.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I don't know of a way to constrain a crop to a particular aspect ratio. Instead I'd suggest creating your own method for cropping images.
I have an app on Github called CropImg that does just that. It doesn't constrain the crop to square, but that would be easy to add.

Profile page swift 3 errors

This is the code that I have created for my profile page but it has some mistakes that i would like to adjust.
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class ProfileClass: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: RoundButton!
#IBOutlet weak var ProfilePicture: RoundImage!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var imageLoader: UIActivityIndicatorView!
var loggedInUser = AnyObject?()
var databaseRef = FIRDatabase.database().reference()
var storageRef = FIRStorage.storage().reference()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).observeSingleEvent(of: FIRDataEventType(.Value) { (snapshot:FIRDataSnapshot) in
if(snapshot.value!["usernameField"] !== nil) {
self.usernameField.text = snapshot.value!["usernameField"] as? String
}
if(snapshot.value!["profile_pic"] !== nil) {
let databaseProfilePic = snapshot.value!["profile_pic"]
as! String
let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)
self.setProfilePicture(self.ProfilePicture,imageToSet:UIImage(data:data!)!)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutTapped(_ sender: Any) {
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
self.performSegue(withIdentifier: "goToLogin", sender: self)
}
#IBAction func TapProfileButton(_ sender: RoundButton) {
let myActionShett = UIAlertController(title:"Profile Picture",message:"Select",preferredStyle: UIAlertControllerStyle.actionSheet)
let viewPicture = UIAlertAction(title: "View Picture", style: UIAlertActionStyle.default) { (action) in
let imageView = sender.view as! RoundImage
let newImageView = RoundImage(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.blackColor()
newImageView.contentMode = .scaleAspectFit
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
let photoGallery = UIAlertAction(title: "Photos", style: UIAlertActionStyle.default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
let camera = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default)
{ (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
myActionShett.addAction(viewPicture)
myActionShett.addAction(photoGallery)
myActionShett.addAction(camera)
myActionShett.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(myActionShett, animated: true, completion: nil)
}
func dismissFullScreenImage(sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.imageLoader.stopAnimating()
setProfilePicture(self.ProfilePicture,imageToSet: image)
if let imageData: NSData = UIImagePNGRepresentation(self.ProfilePicture, image!)!
{
let profilePicStorageRef = storageRef.child("user_profiles/\(self.loggedInUser!.uid)/profile_pic")
let uploadTask = profilePicStorageRef.putData(imageData, metadata: nil)
{metadata,error in
if(error == nil)
{
let downloadUrl = metadata!.downloadUrl()
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).child("profile_pic").setValue(downloadUrl!.absoluteString)
}
else
{
print(error?.localizedDescription)
}
self.imageLoader.stopAnimating()
}
}
self.dismiss(animated: true, completion: nil)
}
}
You have to give proper type. You can not initialize object of type AnyObject. and Obviously with not using AnyObject?.

Swift - UIImagePickerController - how to use it?

I am trying hard to understand how this works, but it's pretty hard for me. =)
I have 1 view, there is one button and one small ImageView area for preview.
The button triggers imagepickercontroller, and the UIView will display picked image.
There is no error but the image doesn't show in the UIImageView area.
var imagePicker = UIImagePickerController()
#IBOutlet var imagePreview : UIImageView
#IBAction func AddImageButton(sender : AnyObject) {
imagePicker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
imagePicker.delegate = self
self.presentModalViewController(imagePicker, animated: true)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
imagePreview.image = tempImage
self.dismissModalViewControllerAnimated(true)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!) {
self.dismissModalViewControllerAnimated(true)
}
You're grabbing a UIImage named UIImagePickerControllerOriginalImage and there exists no such image. You're meant to grab the UIImage with the key UIImagePickerControllerOriginalImage from the editingInfo dictionary:
let tempImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage
Details
Xcode 11.4.1 (11E503a), Swift 5.2
More
How to build own photo picker
Solution
import UIKit
import AVFoundation
import Photos
protocol ImagePickerDelegate: class {
func imagePicker(_ imagePicker: ImagePicker, grantedAccess: Bool,
to sourceType: UIImagePickerController.SourceType)
func imagePicker(_ imagePicker: ImagePicker, didSelect image: UIImage)
func cancelButtonDidClick(on imageView: ImagePicker)
}
class ImagePicker: NSObject {
private weak var controller: UIImagePickerController?
weak var delegate: ImagePickerDelegate? = nil
func dismiss() { controller?.dismiss(animated: true, completion: nil) }
func present(parent viewController: UIViewController, sourceType: UIImagePickerController.SourceType) {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = sourceType
self.controller = controller
DispatchQueue.main.async {
viewController.present(controller, animated: true, completion: nil)
}
}
}
// MARK: Get access to camera or photo library
extension ImagePicker {
private func showAlert(targetName: String, completion: ((Bool) -> Void)?) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
let alertVC = UIAlertController(title: "Access to the \(targetName)",
message: "Please provide access to your \(targetName)",
preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Settings", style: .default, handler: { action in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
UIApplication.shared.canOpenURL(settingsUrl) else { completion?(false); return }
UIApplication.shared.open(settingsUrl, options: [:]) { [weak self] _ in
self?.showAlert(targetName: targetName, completion: completion)
}
}))
alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completion?(false) }))
UIApplication.shared.windows.filter { $0.isKeyWindow }.first?
.rootViewController?.present(alertVC, animated: true, completion: nil)
}
}
func cameraAsscessRequest() {
if delegate == nil { return }
let source = UIImagePickerController.SourceType.camera
if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
delegate?.imagePicker(self, grantedAccess: true, to: source)
} else {
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
guard let self = self else { return }
if granted {
self.delegate?.imagePicker(self, grantedAccess: granted, to: source)
} else {
self.showAlert(targetName: "camera") { self.delegate?.imagePicker(self, grantedAccess: $0, to: source) }
}
}
}
}
func photoGalleryAsscessRequest() {
PHPhotoLibrary.requestAuthorization { [weak self] result in
guard let self = self else { return }
let source = UIImagePickerController.SourceType.photoLibrary
if result == .authorized {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.imagePicker(self, grantedAccess: result == .authorized, to: source)
}
} else {
self.showAlert(targetName: "photo gallery") { self.delegate?.imagePicker(self, grantedAccess: $0, to: source) }
}
}
}
}
// MARK: UINavigationControllerDelegate
extension ImagePicker: UINavigationControllerDelegate { }
// MARK: UIImagePickerControllerDelegate
extension ImagePicker: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.editedImage] as? UIImage {
delegate?.imagePicker(self, didSelect: image)
return
}
if let image = info[.originalImage] as? UIImage {
delegate?.imagePicker(self, didSelect: image)
} else {
print("Other source")
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
delegate?.cancelButtonDidClick(on: self)
}
}
Full Usage
Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>bla-bla-bla</string>
<key>NSCameraUsageDescription</key>
<string>bla-bla-bla</string>
ViewController (do not forget to paste solution code)
import UIKit
class ViewController: UIViewController {
private weak var imageView: UIImageView!
private lazy var imagePicker: ImagePicker = {
let imagePicker = ImagePicker()
imagePicker.delegate = self
return imagePicker
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "camera", style: .plain, target: self,
action: #selector(cameraButtonTapped))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "photo", style: .plain, target: self,
action: #selector(photoButtonTapped))
let imageView = UIImageView(frame: CGRect(x: 40, y: 80, width: 200, height: 200))
imageView.backgroundColor = .lightGray
view.addSubview(imageView)
self.imageView = imageView
}
#objc func photoButtonTapped(_ sender: UIButton) { imagePicker.photoGalleryAsscessRequest() }
#objc func cameraButtonTapped(_ sender: UIButton) { imagePicker.cameraAsscessRequest() }
}
// MARK: ImagePickerDelegate
extension ViewController: ImagePickerDelegate {
func imagePicker(_ imagePicker: ImagePicker, didSelect image: UIImage) {
imageView.image = image
imagePicker.dismiss()
}
func cancelButtonDidClick(on imageView: ImagePicker) { imagePicker.dismiss() }
func imagePicker(_ imagePicker: ImagePicker, grantedAccess: Bool,
to sourceType: UIImagePickerController.SourceType) {
guard grantedAccess else { return }
imagePicker.present(parent: self, sourceType: sourceType)
}
}
Images
import MobileCoreServices
class SecondViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet var img:UIImageView!=nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
#IBAction func buttonTapped(AnyObject)
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
println("Button capture")
var imag = UIImagePickerController()
imag.delegate = self
imag.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
//imag.mediaTypes = [kUTTypeImage];
imag.allowsEditing = false
self.presentViewController(imag, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
let selectedImage : UIImage = image
//var tempImage:UIImage = editingInfo[UIImagePickerControllerOriginalImage] as UIImage
img.image=selectedImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Since swift 4.2 and xcode 10 the func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) change a bit.
at the function header the infoKey-Section changes from
didFinishPickingMediaWithInfo info: [String : Any] to
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]
To get the originalImage you now have to call:
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage or
let image = info[.originalImage] as? UIImage
find other infoKeys here (editedImage, imageURL and more...)
In Swift 5.2, iOS 14.2
class YourViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBAction func btnTapped(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false //If you want edit option set "true"
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let tempImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
imgRoom.image = tempImage
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
Try this:
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
let tempImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imagePreview.image = tempImage
or you can also use ? in place of !.

Resources