Getting error `Do you want to add protocol stubs? [duplicate] - ios

This question already has answers here:
Xcode 8 says "Do you want to add a stub?" How do I answer?
(3 answers)
Closed 4 years ago.
I added the ImageView Protocol. What can be done to remove the error
Do you want to add protocol stubs?
CardsViewController
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageViewProtocol {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var imageView: UIImageView!
#IBAction func goToViewController2Action(_ sender: Any)
{
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewController2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
if UIImagePickerController.isSourceTypeAvailable(source) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = source
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
print("Not all fields are filled")
} else {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
let card = Card(context: context)
card.name = nameTextField.text
card.location = locationTextField.text
card.number = textField.text
if let image = imageView.image {
card.image = image.pngData()
}
do {
try context.save()
print("Cохранение удалось!")
} catch let error as NSError {
print("Не удалось сохранить данные \(error), \(error.userInfo)")
}
}
performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
var filter : CIFilter!
var delegate: ImageViewProtocol!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "photo")
}
#IBAction func saveButtonAction(_ sender: Any) {
if textField.text == "" {
print("Not all fields are filled")
} else {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
barcodeImageView.image = image
}
}
}
}

This error comes because you implemented protocol (ImageViewProtcol) but you haven't add required methods of your protocol (in your case sendImageToViewController(theImage: UIImage)). All methods of your protocol are required by default. If you want to change it, you can look here.
It's the same as when you're implementing UITableViewDataSource, you also need to add required methods like number of items etc.
To fix this, add this method to your CardsViewController:
func sendImageToViewController(theImage: UIImage) {
// do something with image
}

Related

Pass Firebase data from UITableViewCell to ViewController

First post so apologies for anything I do wrong here.
I've been stuck on this for awhile now. I think the problem is pretty straight forward, but I seem to be missing something. The code below is from my homeVC which has a tableview. I created a tableViewCell as well. I have firebase hooked up and the data saves properly. Overall goal is to create a recipe manager. Home screen has a list of recipes, you can add and edit. When you click on the recipe name in the homeVC table you are taken to ShowDataVC. I am able to load the recipe name into the tableview but cant seem to get it to load when selected to the ShowDataVC. Ultimately I think I want to be able to use the UUID I created for each recipe to display all info, handling edits, handling error state if no recipe is found for that ID.
Thanks in advance!
struct RecipeData {
let user: String
let recipeName: String
let ingredientsText: String?
let directionsText: String?
let servingsNumber: Int?
let id = UUID().uuidString
}
import UIKit
import Firebase
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var table: UITableView!
#IBOutlet weak var logout: UIBarButtonItem!
#IBOutlet weak var add: UIBarButtonItem!
let db = Firestore.firestore()
var id = UUID().uuidString
var data = [RecipeData]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray
table.delegate = self
table.dataSource = self
navigationItem.hidesBackButton = true
table.register(UINib(nibName: D.cellNibName, bundle: nil), forCellReuseIdentifier: D.cellIdentifier)
loadRecipeNames()
}
func loadRecipeNames() {
db.collection(D.FStore.collectionName)
.addSnapshotListener { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let data = document.data()
if let user = data[D.FStore.userField] as? String,
let recipeNameLabels = data[D.FStore.recipeTextField] as? String {
//print("This is = \(document.documentID) => \(document.data())")
let newRecipe = RecipeData(user: user, recipeName: recipeNameLabels, ingredientsText: nil, directionsText: nil, servingsNumber: nil)
self.data.append(newRecipe)
DispatchQueue.main.async {
self.table.reloadData()
let indexPath = IndexPath(row: self.data.count - 1, section: 0)
self.table.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
}
}
}
}
#IBAction func logoutPressed(_ sender: UIBarButtonItem) {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print("Error signing out: %#", signOutError)
}
}
#IBAction func addPressed(_ sender: UIBarButtonItem) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: D.addRecipeSegue) as! AddRecipeViewController
navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = data[indexPath.row]
let cell = table.dequeueReusableCell(withIdentifier: D.cellIdentifier, for: indexPath) as! RecipeNameCell
cell.label.text = data.recipeName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "ShowSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowSegue" {
if let indexPath = table.indexPathForSelectedRow {
let vc = segue.destination as! ShowRecipeDataViewController
vc.newData = data[indexPath.row]
}
}
}
}
import UIKit
import Firebase
class AddRecipeViewController: UIViewController, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
#IBOutlet weak var recipeNameTextField: UITextField!
#IBOutlet weak var ingredientsTextField: UITextView!
#IBOutlet weak var directionsTextField: UITextView!
#IBOutlet weak var stepper: UIStepper!
#IBOutlet weak var numServingLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var takePicture: UIButton!
#IBOutlet weak var saveButton: UIBarButtonItem!
let db = Firestore.firestore()
var data: [RecipeData] = []
var stepperValue: Int = 0
var id = UUID().uuidString
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .lightGray
}
#IBAction func savePressed(_ sender: UIBarButtonItem) {
if let text = recipeNameTextField.text, !text.isEmpty {
saveData(text: text)
print("Data successfully saved!")
}
}
func saveData(text: String) {
if let recipeName = recipeNameTextField.text,
let addedIngredients = ingredientsTextField.text,
let directionsText = directionsTextField.text,
let servingsNum = numServingLabel.text,
let user = Auth.auth().currentUser?.email {
let newRecipeRef = db.collection(D.FStore.collectionName).document(id)
newRecipeRef.setData([
D.FStore.recipeTextField: recipeName,
D.FStore.ingredientsText: addedIngredients,
D.FStore.directionsText: directionsText,
D.FStore.numberServings: servingsNum,
D.FStore.userField: user,
D.FStore.id: id
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID:\(newRecipeRef)")
}
}
}
}
#IBAction func takePicturePressed(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {
return
}
guard let imageData = image.pngData() else {
return
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
#IBAction func stepperPressed(_ sender: UIStepper) {
stepperValue = Int(sender.value)
numServingLabel.text = "\(stepperValue)"
}
}
import UIKit
import Firebase
class ShowRecipeDataViewController: UIViewController {
#IBOutlet weak var recipeNameLabel: UILabel!
#IBOutlet weak var ingredientsText: UILabel!
#IBOutlet weak var directionsText: UILabel!
#IBOutlet weak var numServings: UILabel!
#IBOutlet weak var logout: UIBarButtonItem!
let db = Firestore.firestore()
var newData = [RecipeData]()
var data: [RecipeData] = []
var id = UUID().uuidString
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemOrange
}
#IBAction func logoutPressed() {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print("Error signing out: %#", signOutError)
}
}
}
Update
You'll need to assign the values to your outlets. You can do that like so.
class ShowRecipeDataViewController: UIViewController {
#IBOutlet weak var recipeNameLabel: UILabel!
#IBOutlet weak var ingredientsText: UILabel!
#IBOutlet weak var directionsText: UILabel!
#IBOutlet weak var numServings: UILabel!
#IBOutlet weak var logout: UIBarButtonItem!
let db = Firestore.firestore()
var newData: RecipeData? = nil
var data: [RecipeData] = []
var id = UUID().uuidString
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemOrange
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let newData = newData else {
return
}
recipeNameLabel.text = newData.recipeName
ingredientsText.text = newData.ingredientsText
directionsText.text = newData.directionsText
numServings.text = "\(newData.servingsNumber)"
}
#IBAction func logoutPressed() {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print("Error signing out: %#", signOutError)
}
}
}
Original Answer
You'll need to share your ShowRecipeDataViewController code to get a better answer. But, the problem is probably there. But if I had to guess you'll need to add the code to tell the textField or Label to have the data in it.
Often, people do that in the ViewDidLoad function like:
// inside ShowRecipeDataViewController
override func viewDidLoad() {
super.viewDidLoad()
recipeLabel.text = data.recipeName
ingredientsTextField.text = data.ingredients
}
// etc.,

User variable is nil when creating a user with Firebase

I am following a tutorial and cannot seem to register my user as the user variable in the Firebase .createUser method appears to be nil. Therefore, when I unwrap it, I get an error.
I have read through a lot of the documentation as well as checked many other questions similar to mine but nothing seems to work
import UIKit
import Firebase
import SwiftKeychainWrapper
class ViewController: UIViewController {
#IBOutlet weak var userImgView: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
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 let _ = KeychainWrapper.standard.string(forKey: "uid") {
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupUser(userUid: String) {
if let imageData = self.userImgView.image!.jpegData(compressionQuality: 0.2) {
let imgUid = NSUUID().uuidString
let metaData = StorageMetadata()
Storage.storage().reference().child(imgUid).putData(imageData, metadata: metaData) { (metadata, error) in
let downloadURL = metadata
let userData = [
"username": self.usernameField.text!,
"userImg": downloadURL!
] as [String : Any]
Database.database().reference().child("users").child(userUid).setValue(userData)
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
#IBAction func signInPressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password) { user, error in
if error != nil && !(self.usernameField.text?.isEmpty)! {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
self.performSegue(withIdentifier: "toFeed", sender: nil)
let userID = (user?.user.uid)!
self.setupUser(userUid: userID)
KeychainWrapper.standard.set(userID, forKey: "uid")
}
} else {
if let userID = (user?.user.uid) {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
}
}
#IBAction func getPhoto (_ sender: AnyObject) {
present(imagePicker, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
userImgView.image = image
} else {
print("image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
}
The error I am getting is one the "let userID = (user?.user.uid)!". It is
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
The completion block for createUser(withEmail:,password:) gets called with either a AuthResult.user or an error. That why, as Joshua commented, you should check if error is nil before accessing any of the user properties.
From the auth quickstart for Swift:
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
strongSelf.hideSpinner {
guard let user = authResult?.user, error == nil else {
strongSelf.showMessagePrompt(error!.localizedDescription)
return
}
print("\(user.email!) created")
strongSelf.navigationController?.popViewController(animated: true)
}
}

Upload multiple images to Google Drive using API/SDK (IOS, Swift)

I am developing an App that will ask for 5 images, assign them to the proper UIImageViewer for preview purposes, and then I would like to hit upload and all 5 images go to a team drive. At this point all of it works except the code snippet I have is only able to upload images if they are in the App's Documents Directory. I would like to reference back to the 5 previously chosen images and upload them to a team drive but I do not know how to go about that.
Each button has been assigned a tag number, in which will equal their designated UIImageViewer. I am trying to reference the other previously chosen images but an error says in the 'UploadAction' button "Cannot convert value of type 'UIImage' to expected argument type 'String'". Here is my code, any help would be greatly appreciated!! (This is in Swift in Xcode, I could not find any examples using swift to upload pictures using a phone camera or photo gallery)
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GIDSignInUIDelegate, UIPickerViewDelegate, UITextFieldDelegate{
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
//
// }
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//
// }
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
#IBOutlet weak var resultsLabel: UILabel!
var imagePicker = UIImagePickerController()
var imagePicked = 0
var cameraPicker = UIImagePickerController()
var cameraPicked = 0
fileprivate let service = GTLRDriveService()
private var drive: ATGoogleDrive?
override func viewDidLoad() {
super.viewDidLoad()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
cameraPicker.allowsEditing = false; imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false;
GIDSignIn.sharedInstance().uiDelegate = self;
self.view.backgroundColor = UIColor.lightGray;
setupGoogleSignIn()
drive = ATGoogleDrive(service)
}
#IBAction func openCamera(_ sender: UIButton){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
cameraPicked = sender.tag
present(cameraPicker, animated: true)
}
}
#IBAction func chooseImage1(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.savedPhotosAlbum){
imagePicked = sender.tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
let cameraImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
if imagePicked == 1 {
imageView1.image = pickedImage
} else if imagePicked == 2 {
imageView2.image = pickedImage
} else if imagePicked == 3 {
imageView3.image = pickedImage
} else if imagePicked == 4 {
imageView4.image = pickedImage
} else if imagePicked == 5 {
imageView5.image = pickedImage
} else if cameraPicked == 6 {
imageView1.image = cameraImage
} else if cameraPicked == 7 {
imageView2.image = cameraImage
} else if cameraPicked == 8 {
imageView3.image = cameraImage
} else if cameraPicked == 9 {
imageView4.image = cameraImage
} else if cameraPicked == 10 {
imageView5.image = cameraImage
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
private func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = [kGTLRAuthScopeDriveFile]
GIDSignIn.sharedInstance().signInSilently()
}
// MARK: - Actions
**#IBAction func uploadAction(_ sender: Any) {
if let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let uploadem = imageView1.image
drive?.uploadFile("agostini_tech_demo", filePath: uploadem, MIMEType: "image/png") { (fileID, error) in
print("Upload file ID: \(fileID); Error: \(error?.localizedDescription)")**
}
}
}
#IBAction func listAction(_ sender: Any) {
drive?.listFilesInFolder("agostini_tech_demo") { (files, error) in
guard let fileList = files else {
print("Error listing files: \(error?.localizedDescription)")
return
}
self.resultsLabel.text = fileList.files?.description
}
}
}
// MARK: - GIDSignInDelegate
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let _ = error {
// service.authorizer = nil
} else {
// service.authorizer = user.authentication.fetcherAuthorizer()
}
}
}

Issues Uploading Images and posts to Firebase 5 Database

I am currently trying to upload a photo URL and post caption onto my firebase database. The photos are currently being saved on firebase storage which is fine, however I would like for it to also appear on the firebase database.
I repeatedly find myself dealing with this error "Value of type 'StorageMetadata' has no member 'downloadURL'"
I understand that in firebase 5 to get the url from storage you need to call downloadURL on storage reference, not metadata. I have tried multiple ways and examples, but it all leads to errors.screenshot of error
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
#IBOutlet weak var shareButton: UIButton!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto)); photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost() {
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
}else{
self.shareButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
self.removeButton.isEnabled = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
let hud = JGProgressHUD(style: .dark)
hud.textLabel.text = "Loading"
hud.show(in: self.view)
hud.dismiss(afterDelay: 3.0)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1) {
let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: ".......").child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
if error != nil {
return
}
//let photoUrl = url?.absoluteString
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
}
)}
}
#IBAction func remove_TouchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl: String) {
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0 // switches user back to selected tabbar 0 = first 1 = second etc.
})
}
func clean() {
self.captionTextView.text = ""
self.photo.image = UIImage(named:"placeholder-photo")
self.selectedImage = nil
}
}
extension CameraViewController: UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
print("did finish picking media")
if let image = info["UIImagePickerControllerOriginalImage"]
as? UIImage {
selectedImage = image
photo.image = image
}
// profileImage.image = infoPhoto
dismiss(animated: true, completion: nil)
}
}
import UIKit
import ProgressHUD
import FirebaseStorage
import FirebaseDatabase
class CameraViewController: UIViewController {
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var shareButton: UIButton!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto))
photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost(){
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
} else {
self.shareButton.isEnabled = false
self.removeButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto(){
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
// Share photos to the storage database
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
ProgressHUD.show("Please wait...", interaction: false)
if let profileImg = self.selectedImage, let photoData = profileImg.jpegData(compressionQuality: 0.1) {
let photoIdString = NSUUID().uuidString
print(photoIdString)
let storageRef = Storage.storage().reference(forURL:Config.STORAGE_ROOT_REF).child("Posts").child(photoIdString)
storageRef.putData(photoData, metadata: nil, completion: { (metadata, error) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
})
} else {
ProgressHUD.showError("Profile image can't be empty")
}
}
#IBAction func remove_touchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl:String){
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil{
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0
})
}
func clean(){
self.captionTextView.text = ""
self.photo.image = UIImage(named: "placeholder-img")
self.shareButton = nil
}
}
extension CameraViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("did Finish picking media")
if let chosenImage = info[.originalImage] as? UIImage {
selectedImage = chosenImage
photo.image = chosenImage
}
dismiss(animated: true, completion: nil)
}
}
Use Above code, it will successfully upload the image and post that to the Firebase Database

Use of unresolved identifier 'metadata'

I have this code, but I have a problem, because it writes me Use of unresolved identifier 'metadata', Thanks in advance! I am a beginner in Xcode, so please explain well!
I got this out of in a youtube tutorial, from zero2launch!
import UIKit
import FirebaseDatabase
import FirebaseAuth
import FirebaseStorage
class SignUpViewController: UIViewController {
#IBOutlet weak var ProfileImage: UIImageView!
#IBOutlet weak var UsernameField: UITextField!
#IBOutlet weak var PasswordField: UITextField!
#IBOutlet weak var Mailfield: UITextField!
var selectedImage: UIImage?
#IBAction func dismiss_onClick(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
ProfileImage.layer.cornerRadius = 40
ProfileImage.clipsToBounds = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SignUpViewController.handleSelectProfileImageView))
ProfileImage.addGestureRecognizer(tapGesture)
ProfileImage.isUserInteractionEnabled = true
}
#objc func handleSelectProfileImageView() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func SignUpButton(_ sender: Any) {
Auth.auth().createUser(withEmail: Mailfield.text!, password: PasswordField.text! , completion:{(user: User?, error:Error?) in
if error != nil {
print(error!.localizedDescription)
return
}
let uid = user?.uid
let storageRef = Storage.storage().reference(forURL: "gs://gibble-2bed4.appspot.com").child("profile_image").child(uid!)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1){
storageRef.putData(imageData, metadata: nil, completion: { (matadata, error) in
if error != nil{
return
}
let profileImageUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let usersReference = ref.child("users")
let newUserReference = usersReference.child(uid!)
newUserReference.setValue(["username" : self.UsernameField.text!, "email": self.Mailfield.text!, "profileImageUrl": profileImageUrl])
})
}
})
}
}
extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("did Finish picking Media")
if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage{
selectedImage = image
ProfileImage.image = image
dismiss(animated: true, completion: nil)
}
print(info)
}
}
You initialised matadata instead of metadata (which you want to use) in the closure in your following code (first line: "(matadata, error)"):
storageRef.putData(imageData, metadata: nil, completion: { (matadata, error) in
if error != nil{
return
}
let profileImageUrl = metadata?.downloadURL()?.absoluteString
The metadata in the last line should be matadata or you have to change it in the first line.

Resources