How to assign a picture to the UIImageView (Swift 3) - ios

I'm trying to add an image from the gallery to the new ViewController, but get an error
Creating an image format with an unknown type is an error fatal error: unexpectedly found nil while unwrapping an Optional value
Code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let im = info[UIImagePickerControllerOriginalImage] as? UIImage {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "editImage") as! EditImageViewController
vc.imageView.image = im
self.present(vc, animated: true, completion: nil)
} else {
print("Something went wrong")
}
imagePicker.dismiss(animated: true, completion: nil)
}
What's my mistake?

Your EditImageViewController.imageViewis nil.
To pass image from outside, you need to add UIImage property to EditImageViewController.
To assign that image to UIImageView, use viewDidLoad()
Something like this:
class EditImageViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var imageToAdd: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.image = imageToAdd
}
}
To pass image to new controller, just set imageToAdd, so vc.imageView.image = im becomes vc.imageToAdd = im

Related

How to process a taken image then view the results to "text View" using Swift?

I am trying to build a simple app with a single button. Click on the button to take a picture, then using "TesseractOCR" I am converting the written text in the image to a string text and view it in my "Text View".
I got everything done, the camera and "TesseractOCR", the only problem I am facing is the following:
tesseract.image = UIImage(named: selectedImage)
Gives me this error:
Cannot convert value of type 'UIImage' to expected argument type 'String'.
Note: selectedImage suppose to be the name of the image that Tesseract takes to convert the image into text.
Here is my code:
import UIKit
import TesseractOCR
class secondViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, G8TesseractDelegate {
#IBOutlet weak var viewText: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func takePhoto(_ sender: Any) {
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]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
if let tesseract = G8Tesseract(language: "eng") {
tesseract.delegate = self
tesseract.image = UIImage(named: selectedImage)
tesseract.recognize()
textView.text = tesseract.recognizedText
}
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
}
Replace
tesseract.image = UIImage(named: selectedImage)
with
tesseract.image = selectedImage
the UIImage(named:<#string#>) takes a string value repressing the name of the image in bundle , but here you don't need it , instead supply the image directly

Swift 4 errors encountered while discovering extensions - photo will not load on UI

I am getting the following error message when I choose a photo from the photo library to populate a UIImageView in XCode 9.2:
[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
The simulator is able to access the photo library and I am able to view the photos to make a selection, but when I click on the 'Choose' option to select a photo, the error is thrown and after the picker is dismissed the image is not populating the UIImageView.
I have searched Stack Overflow and am able to get rid of the error message if I do this step: From Xcode menu open: Product > Scheme > Edit Scheme > On your Environment Variables set OS_ACTIVITY_MODE in the value set disable. However, this only gets rid of the error and does not fix the issue with my selected photo not populating the UIImageView. I am new to Swift and Xcode and am stuck! Please help!
Here is my code:
import UIKit
class HomeVC: UIViewController, UINavigationControllerDelegate,
UIImagePickerControllerDelegate {
#IBOutlet weak var avaImg: UIImageView!
#IBOutlet weak var usernameLbl: UILabel!
#IBOutlet weak var fullnameLbl: UILabel!
#IBOutlet weak var emailLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//get user details from user global var (from database)
let username = (user!["username"] as? String)?.uppercased()
let fullname = user!["fullname"] as? String
let email = user!["email"] as? String
let ava = user!["ava"] as? String
//populate labels on view
usernameLbl.text = username
fullnameLbl.text = fullname
emailLbl.text = email
}
#IBAction func edit_click(_ sender: AnyObject) {
//select ava
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.allowsEditing = true
self.present(picker, animated: true, completion: nil)
//selected image
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerEditedImage] as?
UIImage
avaImg.image = image
self.dismiss(animated: true, completion: nil)
}
}
}
Two issues:
The signature of didFinishPickingMediaWithInfo is wrong. In Swift 3+ it is
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any])
The delegate method must be on the top level of the class (not in another method)
#IBAction func edit_click(_ sender: Any) {
//select ava
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
self.present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//selected image
let image = info[UIImagePickerControllerEditedImage] as? UIImage
avaImg.image = image
self.dismiss(animated: true, completion: nil)
}

Show image that is selected from UIImagePickerController

The app opens the pickerController and selects the image, but it doesn't show the image that was selected. I tried putting self before image_sel.image = photo, but it didn't work neither. When I put print inside extension it prints and it also hits breakpoints.
lazy var image_sel: UIImageView = {
let i = UIImageView()
i.translatesAutoresizingMaskIntoConstraints = false
i.image = #imageLiteral(resourceName: "noimage")
return i
}()
#objc func imageSelect(){
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
extension CameraPage: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let photo = info["UIImagePickerControllerOriginalImage"] as? UIImage {
image_sel.image = photo
}
dismiss(animated: true, completion: nil)
}
}
lazy var image_sel: UIImageView
You are using a lazy var property, might be the case that you still don't have a object when you try to assign the value to ImageView.
Try to use the image on another UIImageView to see if that's the problem.
Check your view stack
I haven't saw where you display image_sel. Did you use addSubview?

Creating an image format with an unknown type is an error...Swift3

I'm learning some swift 3 following courses on youtube. The code below I've written is for creating a user account and storing details in a Firebase database. When testing, I can progress up to the point of submitting the registration form. I then receive the following error:
[Generic] Creating an image format with an unknown type is an error.
Fatal Error: unexpectedly found nil whilst unwrapping an Optionional value.
I have also had the below on the line highlighted in the codeblock below:
exc_bad_instruction(code=exc_i386_invop subcode=0x0)
Below is my code. I have highlighted where the exception is thrown. Any assistance would be much appreciated.
import UIKit
import Firebase
class Signup_ViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Input data fields for signup form
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var nameField: UITextField!
// Password data field for signup form
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmPasswordField: UITextField!
// Next button for signup form (Hidden by default)
#IBOutlet weak var nextBtn: UIButton!
let picker = UIImagePickerController()
var userStorage: FIRStorageReference!
var ref: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
let storage = FIRStorage.storage().reference(forURL: "XXXXXXXXXXXXXXXXXXXX") // Defines URL for Firebase storage container
ref = FIRDatabase.database().reference()
userStorage = storage.child("users") // Folder on Firebase storage
}
// Image for signup form - user profile image
#IBOutlet weak var imgView: UIImageView!
// Action for when user presses the "Select profile picture" button
#IBAction func selectProfileImagePress(_ sender: Any) {
picker.allowsEditing = true // Enables user to edit photo
picker.sourceType = .photoLibrary // Enables user to pick photo from photo library
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.imgView.image = image // Checks image selected exists
nextBtn.isHidden = false // Unhides "Next" button once image has been picked
}
self.dismiss(animated: true, completion: nil)
}
// Action for when the "Next" button is pressed
#IBAction func nextPressed(_ sender: Any) {
guard usernameField.text != "", nameField.text != "", emailField.text != "", passwordField.text != "", confirmPasswordField.text != "" else { return }
if passwordField.text == confirmPasswordField.text { // Checks password and confirm password match <---- Error highlights this line when the app crashes out.
FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in
if let error = error {
print(error.localizedDescription)
}
if let user = user {
let changeRequest = FIRAuth.auth()!.currentUser!.profileChangeRequest()
changeRequest.displayName = self.nameField.text!
changeRequest.commitChanges(completion: nil)
let imageRef = self.userStorage.child("\(user.uid).jpg") // Creates JPG file for user uploading (user.uid is variable for specific user)
let data = UIImageJPEGRepresentation(self.imgView.image!, 0.5) // Prepares user profile picture to be sent to Firebase. Applies 0.5 compression to image.
let uploadTask = imageRef.put(data!, metadata: nil, completion: { (metadata, err) in
if err != nil {
print(err!.localizedDescription)
}
imageRef.downloadURL(completion: { (url, er) in
if er != nil {
print(er!.localizedDescription)
}
if let url = url {
let userInfo: [String : Any] = ["uid" : user.uid,
"username" : self.usernameField.text!,
"name" : self.nameField.text!,
"urltoImage" : url.absoluteString]
self.ref.child("users").child(user.uid).setValue(userInfo)
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userVC")
self.present(vc, animated: true, completion: nil)
}
})
})
uploadTask.resume()
}
})
} else {
print ("Password does not match")
}
}
}
Instead of your code :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
self.imgView.image = image // Checks image selected exists
nextBtn.isHidden = false // Unhides "Next" button once image has been picked
}
self.dismiss(animated: true, completion: nil)
}
use this one ..
/// what app will do when user choose & complete the selection image :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
/// chcek if you can return edited image that user choose it if user already edit it(crop it), return it as image
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
/// if user update it and already got it , just return it to 'self.imgView.image'
self.imgView.image = editedImage
/// else if you could't find the edited image that means user select original image same is it without editing .
} else if let orginalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
/// if user update it and already got it , just return it to 'self.imgView.image'.
self.imgView.image = orginalImage
}
else { print ("error") }
/// if the request successfully done just dismiss
picker.dismiss(animated: true, completion: nil)
}
And for this error :
Creating an image format with an unknown type is an error…Swift3
It's a bug in xcode , if picker could select and return images properly that means everything is okay , just ignore it .

UIImageView not updating image

I am trying to make a simple "Profile" view that allows the user to change his picture. the image picker loads the gallery successfully and i choose the new image then write it to documents directory to load it in next launch, the problem is the imageview is not refreshing with the new image until i exit the app and relaunch again (only viewDidLoad works but viewWillAppear is loading the old image although it is overwritten!) any ideas?
import UIKit
class Profile: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var imagePicker:UIImagePickerController=UIImagePickerController()
var pickedImage:UIImage?
let filemgr = NSFileManager.defaultManager()
#IBOutlet weak var profilepic: UIImageView!
#IBOutlet weak var lblheight: UILabel!
#IBOutlet weak var lblwidth: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
profilepic.layer.borderWidth=1
profilepic.layer.borderColor=UIColor.blackColor().CGColor
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
profilepic.userInteractionEnabled = true
profilepic.addGestureRecognizer(tapGestureRecognizer)
imagePicker.delegate=self
if profileImageExists()
{
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
} else {
pickedImage=UIImage(named:"camera.png")!
}
profilepic.image=pickedImage
}
func imageTapped(img: AnyObject)
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion:
{
self.lblheight.text="completed"
print ("completed image tab")
}
)
}
override func viewWillAppear(animated: Bool) {
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
profilepic.image=pickedImage
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = pickedImage
if let data = UIImagePNGRepresentation(pickedImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func profileImageExists() -> Bool
{
if let profileImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))
{
return true
}
else
{
return false
}
}
}
Loading an UIImage with init(named:) caches the image. So as long as the image name does not change or the system is emptying the cache (for example when you restart the app) the image will be used from the cache and not loaded again.
Try to use init(contentsOfFile:) instead to load the image.
Try updating your imagePickerController method. You have used pickedImage as an instance variable and an local optional variable. I have used newImage instead.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let newImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = newImage
pickedImage = newImage
if let data = UIImagePNGRepresentation(newImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}

Resources