Swift image picker not working - ios

I have look this code several times, even for hour now, but I can find error. :(
There is no error compiling project, no error showing at all, but I just can not pick image, when I press UIImage, nothing happened.
Have similar code in "signUp View Controller" when signing up everything goes well, you can choose (pick) image, and image is properly saved on Firebase.
Also, in this "ProfileTableViewController", everything is show very well, saved image on Firebase is loaded and shown inside Profile View, but can not pick it (press on it) to choose it and change.
Everything else is tested, changed and saved (username or even e-mail), only image gives me problem. Can you please look the code and tell me what I am doing wrong?
Thanks.
import UIKit
class ProfileTableViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var email: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Edit Profile"
let tap = UITapGestureRecognizer(target: self, action: #selector(ProfileTableViewController.selectPhoto(_:)))
tap.numberOfTapsRequired = 1
profileImage.addGestureRecognizer(tap)
profileImage.layer.cornerRadius = profileImage.frame.size.height / 2
profileImage.clipsToBounds = true
if let user = DataService.dataService.currentUser {
username.text = user.displayName
email.text = user.email
if user.photoURL != nil {
if let data = NSData(contentsOfURL: user.photoURL!) {
self.profileImage!.image = UIImage.init(data: data)
}
}
} else {
// No user is signed in
}
}
func selectPhoto(tap: UITapGestureRecognizer) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePicker.sourceType = .Camera
} else {
imagePicker.sourceType = .PhotoLibrary
}
self.presentViewController(imagePicker, animated: true, completion: nil)
}
// UIImagePicker Delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
profileImage.image = image
dismissViewControllerAnimated(true, completion: nil)
}

You need to enable user interaction on the UIImageView, try this after adding gesture recognizer:
profileImage.userInteractionEnabled = true

I did it Other way by Checking User Interaction Enabled under "Interaction" option, see below image for reference
Hope it help anybody

Related

I get "boringssl" error when uploading image to Firebase for iOS

I'm simply trying to upload an image but I'm getting this error "[boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics
Optional("User does not have permission to access 'here was the link to the folder.' ")"
My goal is to upload a photo and access it later from another page, but now I'm getting this error.
edit: Later I realized that I am getting some of the same error while signing up "[boringssl] boringssl_metrics_log_metric_block_invoke(153)".
The entered user can register and appears in the Firebase interface, but the above error is displayed on the console.
import UIKit
import Firebase
class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var commentText: UITextField!
#IBOutlet weak var uploadVar: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
imageView.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(chooseImage))
imageView.addGestureRecognizer(gestureRecognizer)
}
#IBAction func UploadClicked(_ sender: Any) {
let storage = Storage.storage()
let storageReferance = storage.reference()
let mediaFolder = storageReferance.child("media")
if let data = imageView.image?.jpegData(compressionQuality: 0.5) {
let imageReferance = mediaFolder.child("image.jpg")
imageReferance.putData(data, metadata: nil) { metaData, error in
if error != nil {
print(error?.localizedDescription)
} else {
imageReferance.downloadURL { url, error in
if error == nil {
let imageURL = url?.absoluteString
print(imageURL)
}
}
}
}
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[.originalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
#objc func chooseImage() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = .photoLibrary
present(pickerController, animated: true, completion: nil)
}
}

IOS Firebase storage file upload - object does not exist

I'm trying to use Firebase on IOS (Swift) to upload an image file chosen by the user to the firebase storage.
I've already authenticated the user, so that is not the problem.
Below you can see the view controller that I'm trying to use, but when it tries to upload the image, I get back an error message saying:
Object images/vesVLmkqS2cCLQTJOjv9CFe8mh22/0524729A-855E-4E63-8C11-50F4C4B1A905 does not exist.
(you can see in the code that the middle part of this path is the user uid, so I definitely have an authenticated user)
I tried to simplify this path before to test value like "myimage.png" but didn't help, I got the same error.
I've already tried everything I could, please help me because I can't find anything related in the firebase documentation.
The code below automatically opens the image picker when the view loads. If the user chooses an image, we set it to an image view. When the user clicks the upload button, the controller tries to upload the file to firebase storage.
import UIKit
import Firebase
class ShareViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
#IBAction func onPictureTapped(_ sender: Any) {
present(imagePicker, animated: true, completion: nil)
}
#IBAction func onUploadClicked(_ sender: Any) {
if let pickedImage = imageView.image, let imageData = UIImagePNGRepresentation(pickedImage) {
let storageRef = Storage().reference()
let imageRef = storageRef.child("images/\(Auth.auth().currentUser!.uid)/\(NSUUID().uuidString)")
imageRef.putData(imageData, metadata: nil) { (metadata, error) in
if error != nil {
NSLog(error!.localizedDescription)
}
self.navigationController?.popToRootViewController(animated: true)
}
}
}
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.contentMode = .scaleAspectFit
imageView.image = pickedImage
}
self.dismiss(animated: true, completion: nil)
}
}
Ok, I found the problem:
// Instead of this:
Storage().reference()
// You need to use this
Storage.storage().reference()
This is ridiculous that there are no warnings about this, also the app don't crash. Very annoying, and it took me at least 5 hours to find

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 .

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)
}
}
}

Resources