Swift - FireBase - Snapshot - DataService - swift

I have some problems retrieving snapshots from my FireBase child ("Users" into my UITextFields and UITextViews
After I retrieve them, I want them to be editable through code in DataService
Can anyone help ??????
enter code here
import UIKit
import Firebase
class ProfileTableViewController: UITableViewController, UINavigationControllerDelegate, UITextViewDelegate, UITextFieldDelegate {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var email: UITextField!
var imagePicker = UIImagePickerController()
var selectPhoto: UIImageView!
#IBOutlet weak var schoolProfile: UITextField!
#IBOutlet weak var interestProfile: UITextView!
#IBOutlet weak var aboutProfile: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "EDIT PROFILE"
profileImage.layer.cornerRadius = profileImage.frame.size.height / 2
profileImage.clipsToBounds = true
// Display data in tabletcells
if let user = DataService.dataService.currentUser {
username.text = user.displayName
email.text = user.email
// schoolProfile.text = user.School
// print(user.photoURL)
if user.photoURL != nil {
if let data = NSData(contentsOf: user.photoURL!) {
self.profileImage.image = UIImage.init(data: data as Data)
}
}
}else {
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo image: UIImage, editingInfo: [String: Any]?) {
profileImage.image = image
imagePicker.dismiss(animated: true, completion: nil)
}
}
// Change profileimage
#IBAction func selectPhoto(_ sender: UITapGestureRecognizer) {
resignFirstResponder()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.sourceType = .camera
}else {
imagePicker.sourceType = .photoLibrary
}
self.present(imagePicker, animated: true, completion: nil)
}
#IBAction func saveDidTapped(_ sender: AnyObject) {
var data = NSData()
data = UIImageJPEGRepresentation(profileImage.image!, 0.1)! as NSData
DataService.dataService.SaveProfile(username: username.text!, email: email.text!, data: data)
}
}
extension ProfileTableViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo image: UIImage, editingInfo: [String: Any]?) {
profileImage.image = image
imagePicker.dismiss(animated: true, completion: nil)
}
}

Related

Cannot infer contextual base in reference to member 'originalImage'

im trying to use imagePickerController and im getting this weird error "Cannot infer contextual base in reference to member 'originalImage'"
I've used this code before but im not sure why im getting this error this time, or how to fix it.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
guard let pickImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
photoImageView.image = pickImage
dismiss(animated: true, completion: nil)
}
please help!
heres the full code:
class AddCardViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var saveButton: UIBarButtonItem!
#IBOutlet weak var questionField: UITextField!
#IBOutlet weak var answerField: UITextField!
#IBOutlet weak var photoImageView: UIImageView!
private let imagePickerController = UIImagePickerController()
let defaultImage = UIImage(named: "q")
private var newCard: Card?
private func updateSaveButtonState() {
let questionText = questionField.text ?? ""
let answerText = answerField.text ?? ""
saveButton.isEnabled = !questionText.isEmpty && !answerText.isEmpty
}
public func getCard() -> Card? {
return newCard
}
override func viewDidLoad() {
super.viewDidLoad()
photoImageView.image = defaultImage
questionField.delegate = self
answerField.delegate = self
}
#IBAction func pickImage(_ sender: Any) {
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let pickImage:UIImage = info [.originalImage] as? UIImage else {
fatalError("expected a dictionary containing an image, but was provided the following: \(info)")
}
photoImageView.image = pickImage
dismiss(animated: true, completion: nil)
}
func alertMessage(_ message: String) {
let alertController = UIAlertController(title: "Add a card", message: message, preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "okie dokie", style: UIAlertAction.Style.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
I just checked your code and it works for me.
It could be that you don't have an IBOutlet for photoImageView
If it isn't that, then I would need to see the rest of your imagePickerController code to understand what's wrong.
The issue was I was using Swift 4 when I should've been using Swift 5.

Swift Error: EXC BAD INSTRUCTION code=EXCI386 for userid

I am writing an app login page when I countered this error. I do not know how to debug it so I am asking where I coded wrong. I got a problem on the keychain wrapper code:
KeychainWrapper.standard.set((user?.uid)!,forKey: "uid")
I am following a YouTube tutorial on Swift 4, the most updated version. However, it seems this line of code has some problems, therefore I would like to know the problem in the whole code, whether I missed I bracket or failed to import.
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseCore
import SwiftKeychainWrapper
import FirebaseStorage
class ViewController: UIViewController {
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var userimageview: UIImageView!
var imagePicker: UIImagePickerController!
var selectedImage = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
if KeychainWrapper.standard.object(forKey: "KEY_UID") != nil {
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
func storeuserdata(userId: String) {
if let imageData = UIImageJPEGRepresentation(selectedImage, 0.2) {
Storage.storage().reference().putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata.downloadURL
Database.database().reference().child("users").child(userId).setValue(["username": self.usernameField.text!,"userImg": downloadURL
])
}
}
}
#IBAction func signinpressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error != nil && (self.usernameField.text?.isEmpty)! && self.userimageview.image != nil {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
self.storeuserdata(userId: (user?.uid)!)
KeychainWrapper.standard.set((user?.uid)!,forKey: "uid")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}else {
KeychainWrapper.standard.set((user?.uid)!,forKey: "uid")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
}
#IBAction func getPhoto (_ sender: AnyObject) {
present(imagePicker, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImage = image
}
imagePicker.dismiss(animated: true, completion: nil)
}
}

How to pass the variable from a ViewController Class to other Struct?

I have no idea how to pass the data from the class to another struct. This is my ViewController.swift file. And I have another file called Meme.swift which is used to save the struct. I tried to put the struct in ViewController.swift file as well as Meme.swift file but I cannot access the value like topTextField.text and lowTextField.text and use them in the struct. Can anyone help me with this?
ViewController:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraButton: UIBarButtonItem!
#IBOutlet weak var bottomTextField: UITextField!
#IBOutlet weak var topTextField: UITextField!
#IBOutlet weak var imagePickerView: UIImageView!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var actionButton: UIBarButtonItem!
let bottomTextFieldDelegate = BottomTextFieldDelegate()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
topTextField.delegate = self
bottomTextField.delegate = self.bottomTextFieldDelegate
}
func textFieldDidBeginEditing(_ textField: UITextField) {
topTextField.text = ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
textField.resignFirstResponder()
actionButton.isEnabled = true
return true
}
#IBAction func shareAction(_ sender: Any) {
let image = generateMemedImage()
let controller = UIActivityViewController(activityItems: [image as Any], applicationActivities: nil)
self.present(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = {(activityType: UIActivityType?, completed:Bool, returnedItems:[Any]?, error: Error?) in
if !completed {
debugPrint("cancelled")
return
}else{
self.save()
self.dismiss(animated: true, completion: nil)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
configureTextField(textField: topTextField)
configureTextField(textField: bottomTextField)
topTextField.textAlignment = .center
bottomTextField.textAlignment = .center
subscribeToKeyboardNotifications()
actionButton.isEnabled = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
func configureTextField(textField: UITextField) {
textField.defaultTextAttributes = memeTextAttributes
}
func save() -> Meme {
// Create the meme
let memedImage = generateMemedImage()
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: memedImage)
return meme
}
func generateMemedImage() -> UIImage {
// TODO: Hide toolbar and navbar
navigationController?.setToolbarHidden(true, animated: true)
self.navigationController?.isNavigationBarHidden = true
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// TODO: Show toolbar and navbar
navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.isNavigationBarHidden = false
return memedImage
}
func keyboardWillShow(_ notification:Notification) {
view.frame.origin.y = 0 - getKeyboardHeight(notification)
}
func keyboardWillHide(_ notification:Notification) {
view.frame.origin.y = 0
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat { //getting the height of keyboard and use it for func keyboardWillShow to relocate
//the keyboard using keyboardWillShow function
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
func subscribeToKeyboardNotifications() { //setting up the obeserver to be notified when keyboard is shown or not, then execute keyboardWillShow function
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() { //unsubscribe the notification
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
//setting the arributes of the text
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: 3,]
#IBAction func pickAnImageFromAlbum(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
#IBAction func pickAnImageFromCamera(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imagePickerView.image = image
imagePickerView.contentMode = .scaleAspectFit
dismiss(animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
dismiss(animated: true, completion: nil)
}
}
BottomFieldDelegate:
import Foundation
import UIKit
class BottomTextFieldDelegate: NSObject, UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let viewController = ViewController()
textField.resignFirstResponder()
viewController.view.endEditing(true)
let actionButton = viewController.actionButton
actionButton?.isEnabled = true
return true
}
}
First u need to move this function like save() and generateMemedImage() into your ViewController class and then you can access topTextField.text and lowTextField.text
Modify your struct like below, and do not put nsobject in struct
struct Meme {
var topText: String
var bottomText: String
var memedImage: UIImage
var originalImage: UIImage
init(topText: String, bottomText: String, originalImage: UIImage, memedImage: UIImage) {
self.topText = topText
self.bottomText = bottomText
self.originalImage = originalImage
self.memedImage = memedImage
}
}
Remove save() from Meme struct and put that code in your Viewcontroller file.
Modify your function which return Meme struct object.
func save() -> Meme {
// Create the meme
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: memedImage)
return meme
}
And you can store in Array like below.
let array:[Meme] = []
array.append(save())

How to pass image data from ImagePicker(UIViewController) to UIView

So im trying to pass my image data from the ImagePicker that i selected to my UIbutton on my UIView. I have search it but i am not familiar on how to use delegates and core data. If there is an much more easy and simple way to do that can you help me. BTW i am using ImagePicker Library. I just want to pass my AddItemPhotos images to my btn_firstPhoto and btn_secondPhoto. Thank you in advance
class AddItemImage: UIView {
#IBOutlet weak var btn_firstPhoto: UIButton!
#IBOutlet weak var btn_secondPhoto: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// btn_firstPhoto.setImage(AddItemPhotos[0], for: UIControlState)
// btn_secondPhoto.setImage(AddItemPhotos[1], for: UIControlState)
}
}
class AddItemView: UIViewController, ImagePickerDelegate {
var AddItemPhotos: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
setupPicker()
}
func setupPicker() {
var config = Configuration()
config.doneButtonTitle = "Finish"
config.noImagesTitle = "Sorry! There are no images here!"
config.recordLocation = false
config.allowMultiplePhotoSelection = true
let imagePicker = ImagePickerController()
imagePicker.delegate = self
imagePicker.imageLimit = 2
present(imagePicker, animated: true, completion: nil)
}
// MARK: - ImagePickerDelegate
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
}
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
AddItemPhotos = images
imagePicker.dismiss(animated: true, completion: nil)
}

Value of Type 'uiStackView' Has No Member 'image'

import UIKit
// MARK: Properties
class ViewController: UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
#IBOutlet weak var nameTextField:UITextField!;
#IBOutlet weak var mealNameLabel: UILabel!
#IBOutlet weak var photoImageView: UIStackView!
#IBAction func setDefaultLabelText(sender: UIButton)
{
mealNameLabel.text = "Default Text"
}
override func viewDidLoad()
{
super.viewDidLoad()
//self = viewController
nameTextField.delegate = self
}
//UItextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
//keyboard goes when done
textField.resignFirstResponder()
return true
}
func imagePickController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.photoImageView.image = selectedImage
dismissViewControllerAnimated(true, completion: nil)
}
I am working on the tutorial for Xcode and am running into the issue I listed above. Any help would be appreciated. Thanks!
Shouldn't photoImageView be a UIImageView then?
#IBOutlet weak var photoImageView: UIImageView!