Swift4 imagepicker giving me "Class 'viewcontroller' has no initializers" - ios

I just started to learn swift and have almost no background on developing.
I'm making an app which involves image picker.
While making such function, I get this message saying Class 'viewcontroller' has no initializers.
How do I initialize viewcontroller?
I've searched other posts, but due to my lack of knowledge on developing languages, I'm having hard time understanding the solution.
Thanks in advance.
import UIKit
import MobileCoreServices
class viewcontroller: UIViewController, UINavigationControllerDelegate,
UIImagePickerControllerDelegate {
#IBOutlet var imgView: UIImageView!
let imagepicker: UIImagePickerController! = UIImagePickerController()
var captureimage: UIImage
var videoURL: URL!
var flagImageSave = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnCaptureImageFromCamera(_sender:UIButton) {
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
flagImageSave = true
imagepicker.delegate = self
imagepicker.sourceType = .camera
imagepicker.mediaTypes = [kUTTypeImage as String]
imagepicker.allowsEditing = false
present (imagepicker, animated: true, completion: nil)
}
}
#IBAction func btnLoadImageFromLibrary(_sender: UIButton) {
flagImageSave = false
imagepicker.delegate = self
imagepicker.sourceType = .photoLibrary
imagepicker.mediaTypes = [kUTTypeImage as String]
imagepicker.allowsEditing = true
present (imagepicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as NSString as String) {
captureimage = info[UIImagePickerControllerOriginalImage] as! UIImage
if flagImageSave {
UIImageWriteToSavedPhotosAlbum(captureimage, self, nil, nil)
}
imgView.image = captureimage
}
}
}
func btnCaptureImageFromCamera(_ sender: UIButton) {
}
func btnLoadImageFromLibrary(_ sender: UIButton) {
}

Firstly, style should be ViewController (not viewcontroller), and ideally more descriptive like TheImageViewController but anyway...
At a guess the issue is:
var captureimage: UIImage
Try:
var captureimage: UIImage?
As you have a non-primitive type, that is not ? or ! (read swift docs)

This happens because you declared captureimage property as non optional but haven't provided any instances of this property. To fix this you can either provide default value
var captureimage: UIImage = UIImage()
or make captureimage property optional
var captureimage: UIImage?

Related

imagePickerController - didFinishPickingMediaWithInfo does not get called after picking media

converted app from swift 3 to swift 4.2.
my app had a upload your profile image feature that is not working anymore and I am trying to figure out why. For now What I see is that
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo
didFinishPickingMediaWithInfo Is not being called after media was chosen
Here is my views full code:
import UIKit
class CameraMenuViewController: BaseViewController, 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.openViewControllerBasedOnIdentifier("Home")
//let data = UIImagePNGRepresentation(myImageView) as NSData?
let image = myImageView.image!.pngData() as NSData?
//if let data = UIImagePNGRepresentation(myImageView) {
print("callback data")
let userDetails:Dictionary = (UserDefaults.standard.value(forKey: "myUserDetails") as? [String:Any])!
let UserID:Int = userDetails["UserID"] as! Int
print("UserID")
print(UserID)
print("is_selfie from callback")
//save profile image as NewUserID
UserDefaults.standard.set(image, forKey: String(UserID))
UserDefaults.standard.synchronize()
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) {
print("photo shoot")
//UserDefaults.standard.set("selfie", forKey: "is_selfie")
UserDefaults.standard.set(true, forKey: "is_selfie")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.picker.allowsEditing = false
self.picker.sourceType = UIImagePickerController.SourceType.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()
// Do any additional setup after loading the view, typically from a nib.
picker.delegate = self
DispatchQueue.global(qos: .userInitiated).async
{
self.present(self.picker, animated: true, completion: nil)
}
let language = UserDefaults.standard.object(forKey: "myLanguage") as! String
if(language=="arabic"){
//from_camera.setTitle("كاميرا",for: .normal)
//from_gallery.text.setTitle("الصور",for: .normal)
btn_end.setTitle("إنهاء",for: .normal)
}
}
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[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage //2
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)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
Please help me understand why didFinishPickingMediaWithInfo isn't getting called anymore
It appears as though the function declaration changed between Swift 3 and 4.2. This mustn't have been updated for you by the Swift Migrator Tool. One trick I do when this happens, to check what the correct function declaration is, is to use multiline comment syntax to comment out your current function (didFinishPickingMediaWithInfo in your case). Then you can start typing the function out again, and use Xcode autocomplete to ensure you have it correct. You can then copy the contents of the function you commented out to this new and correct function declaration.
Or - you could just look it up the documentation! According to the documentation on imagePickerController, the function should be declared as:
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
If you replace your function declaration with the above, it should get called again.
As Craig said you need to change delegate function declaration and also afterwards you need to update the following:
let chosenImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
These two changes combined should solve your issue.
i think the name off the function is update
this is my code in My app And work greate
extension FCViewController: UIImagePickerControllerDelegate
{
internal func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
if let photo = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
// Any Code Here ...

Why doesn't UIImagePickerController delegate to my Object class?

class CameraPicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
weak var viewController:MyProfileVC!
func launchCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front
imagePicker.cameraCaptureMode = .photo
imagePicker.allowsEditing = false
self.viewController.present(imagePicker, animated: true, completion: nil)
} }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("didFinishPickingMedia")
}
This is my object class function, but 'didFinishPickingMediaWithInfo' function doesn't get called after taking the picture. Also, the viewcontroller which is presenting the imagepicker is a different Swift file
I had the same problem and I've found a solution, so I'm posting my version (I'm taking a picture from the photo library but it's the same :) ).
I had a memory management issue.
I've created an IBAction function where I instantiated my camera handler class (with the delegate inside...). At the end of the function the variable goes out of scope and it's deallocated. To solve the issue I've made it as instance variable.
That's my code for the VC with my UiButton:
class STECreateUserVC: UIViewController {
#IBOutlet weak var imgAvatar: UIImageView!
let cameraHandler = STECameraHandler()
#IBAction func buttonPressed(_ sender: UIButton) {
cameraHandler.importPictureIn(self) { [weak self] (image) in
self?.imgAvatar.image = image
}
}
}
...and that's my handler:
class STECameraHandler: NSObject {
let imagePickerController = UIImagePickerController()
var completitionClosure: ((UIImage) -> Void)?
func importPictureIn(_ viewController: UIViewController, completitionHandler:((UIImage) -> Void)?) {
completitionClosure = completitionHandler
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
viewController.present(imagePickerController, animated: true, completion: nil)
}
}
extension STECameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let completitionClosure = completitionClosure, let image = info[UIImagePickerControllerEditedImage] as? UIImage {
completitionClosure(image)
}
imagePickerController.dismiss(animated: true)
}
}
I've used a closure in order to have a cleaner code.
This:
self.viewController.present(imagePicker, animated: true, completion: nil)
should be:
self.present(imagePicker, animated: true, completion: nil)

Insert an Image into PDF file Swift

I have searched a lot of pages but haven't seen any good explanation for making image to pdf. Also there are many never answered question. So it's looks helpful to ask here. The app has 'Camera', 'Photo Library' and 'Create PDF' buttons. After taken/choosing picture I want to attach this image into pdf file by 'Create PDF' button
Main Storyboard:
ViewController:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var PhotoLibrary: UIButton!
#IBOutlet weak var Camera: UIButton!
#IBOutlet weak var ImageDisplay: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Photo Library Button Action
#IBAction func PhotoLibraryAction(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
}
//MARK: Camera Button Action
#IBAction func CameraAction(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true, completion: nil)
}
//MARK: Adding Texts on Selected/Taken Image
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {
ImageDisplay.image = image
}
dismissViewControllerAnimated(true, completion: nil)
}
}
Use the following function to convert your image into pdf
func createPdfFromView(imageView: UIImageView, saveToDocumentsWithFileName fileName: String)
{
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, imageView.bounds, nil)
UIGraphicsBeginPDFPage()
let pdfContext = UIGraphicsGetCurrentContext()
if (pdfContext == nil)
{
return
}
imageView.layer.renderInContext(pdfContext!)
UIGraphicsEndPDFContext()
if let documentDirectories: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
{
let documentsFileName = (documentDirectories as! String) + ("/\myPDFImage.pdf")
debugPrint(documentsFileName, terminator: "")
pdfData.writeToFile(documentsFileName, atomically: true)
}
}
I create pdf of a view, so I pass a UIView to this function. Pass your UIImageView to this function and it should work fine.

Why is my data is not writing to Firebase - App crashes due to setObjectForKey: key cannot be nil

for the past two weeks i've been having a struggle to write data to firebase, although the tutorials seem so simple :/....My app has a view controller and a tableview controller. users can add an event Title, event date and description (strings) and add a picture as well. Whenever i try to run the simulator it crashes on me! See code below. Please please help me out this is really getting frustrating.. Even if I place breakpoints in the code on top it crashes.. If someone can help me in a chat that would be awesome or maybe send the file to cause its been too long seriously I need an answer so i understand the problem.
import UIKit
import Firebase
import FirebaseDatabaseUI
class EventViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//outlets for text & image
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var eventName: UITextField!
#IBOutlet weak var eventDate: UITextField!
#IBOutlet weak var eventDes: UITextView!
//Database connection
let rootref = FIRDatabase().reference()
var imagePicker: UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func submitEvent(sender: AnyObject) {
let name = eventName.text
let date = eventDate.text
let text = eventDes.text
var data: NSData = NSData()
var user = NSDictionary()//declare here
if let image = photoImageView.image {
data = UIImageJPEGRepresentation(image,0.1)!
}
let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
if let unwrappedName = name , unwrappedDate = date, unwrappedText = text{
//use your declared dictionary
user = ["name":unwrappedName, "date":unwrappedDate, "text":unwrappedText, "photoBase64":base64String]
}
//Add firebase child node
//let event = FIRDatabase().reference().child(name!)
//Do not create one more reference to database
rootref.child(name!)
rootref.child(name!).setValue(user)
navigationController?.popViewControllerAnimated(true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
//UIImagePickerControllerDelegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func addPicture(sender: AnyObject) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
} else {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion:nil)
}
}
}

Three images using image picker

I am building an app that allows user to add three pictures to threeUIImageViews
I added three buttons, for instance, when a user clicks on button one he should be able to add an image toUIImageView 1
but the image did not come to theUIImageView and I did not find any solution
sample of code:
#IBAction func imageOneBtn(sender: AnyObject) {
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
picker.delegate = self
picker.allowsEditing = false
self.presentViewController(picker, animated: true, completion: nil)
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageViewOne.image = selectedImage
imageViewOne.contentMode = UIViewContentMode.ScaleAspectFit
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
Thank you in advance
The code seems to be correct.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
Try removing the exclamation mark (!).
Try using imageViewOne.contentMode = .ScaleAspectFit
Also try using var instead of let selectedImage
In general Try this code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var selectedImage = info[UIImagePickerControllerOriginalImage] as UIImage
imageViewOne.contentMode = .ScaleAspectFit
imageViewOne.image = selectedImage
dismissViewControllerAnimated(true, completion: nil)
}
I have solved my problem, and this is the answer for anyone who may want to use it
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var oneImg: UIImageView!
#IBOutlet weak var twoImg: UIImageView!
#IBOutlet weak var threeImg: UIImageView!
var num=0;
func config() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .PhotoLibrary
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func oneBtn(sender: AnyObject) {
num = 1
config()
}
#IBAction func twoBtn(sender: AnyObject) {
num = 2
config()
}
#IBAction func threeBtn(sender: AnyObject) {
num = 3
config()
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage;
if num == 1 { // switch can be used here
oneImg.image = selectedImage;
} else if (num == 2) {
twoImg.image = selectedImage
} else if (num == 3) {
threeImg.image = selectedImage
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
}

Resources