What does User? has no member 'profileimageView' mean? - ios

I am unable to understand what exactly the error is trying to tell me. I tried fixing it by using self and changing classes. Still will not help. Need a guide that could help understand what exactly I am missing or doing wrong.
import UIKit
import Foundation
import Firebase
extension LoginController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
func handleRegister(){
guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text
else {
print("This form is not valid")
return
}
Auth.auth().createUser(withEmail: email, password: password) { (self, error) in
if error != nil {
print(error!)
return
}
guard let uid = self?.uid else{
return
}
//sucessfully authenticated user
let storageRef = Storage.storage().reference()
// On the following line
if let uploadData = UIImagePNGRepresentation(self.profileImageView.image!) {
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil{
print(error)
return
}
})
}
let ref = Database.database().reference(fromURL: "https://bbooks-96cac.firebaseio.com/")
let userReference = ref.child("user").child(uid)
let values = ["name": name, "email": email]
userReference.updateChildValues(values, withCompletionBlock: {
(err, ref) in
if err != nil {
print(err)
return
}
// print("Saved user successfully into firebase DB")
})
}
dismiss(animated: true, completion: nil)
}
}

First, you are misusing the term self (I'm surprised there is no error here). You need a better variable name:
Auth.auth().createUser(withEmail: email, password: password) { (self, error) in
I would change self to user here and throughout what follows:
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
Second, user is then an Optional so you need to unwrap it:
if let uploadData = UIImagePNGRepresentation(user!.profileImageView.image!) {

Related

Trying To createUser with Firebase and when i am using Auth.auth().createUser(withEmail: email, password: password) give me an error

enter image description here
#error >> Type of expression is ambiguous without more context.
Auth.auth().createUser(withEmail: email, password: password) { AuthDataResult, error in
// handle error
if let error = error {
print("Failed to create a user with error", error.localizedDescription)
return
}
// set profile image
guard let profileImage = self.plusPhotoButton.imageView?.image else { return }
//upload data
guard let uploadData = profileImage.jpegData(compressionQuality: 0.3) else { return }
// place image in database
let filename = NSUUID().uuidString
let storageRef = Storage.storage().reference().child("profile_image").child(filename)
storageRef.putData(uploadData, metadata: nil, completion: {(metadata, error) in
// handle error
if let error = error {
print("Faild to upload image to firebase storage with error", error.localizedDescription)
}
// profile image URL
guard let profileImageURL = metadata?.downloadURL()?.absoluteString else { return }
//user Id
guard let uid = AuthDataResult?.user.uid else { return }
//guard let fcmToken = messaging.messagin().fcmToken else { return }
let dictionaryValues = ["name": fullName,
"username": username,
"profileImageURL": profileImageURL]
let values = [uid: dictionaryValues]
//save data info to database
Database.database().reference().child("users").updateChildValues(values, withCompletionBlock: { (error, ref) in
print("Successfully created user and saved indformation to database")
})
})
}
i import Firebase but still not working.

Trying to add an image to Firebase storage then add the image location to a Firestore document

I am trying to add an image to Firebase storage and then get the location of that image and store it in a Firestore document with the other user profile data. I am trying to do all of this when the user first creates an account. I was trying to use the image URL to do this but that does not appear to be working. When I run the code below it will sign up a new user and add the photo to Firebase storage but no document gets created in the Firestore database. What am I doing wrong?
#objc func handleSignUp() {
//Signup properties
guard let email = emailTextField.text else { return }
guard let password = passwordTextField.text else { return }
guard let fullName = fullNameTextField.text else { return }
guard let username = usernameTextField.text?.lowercased() else { return }
createUser(email: email,
password: password,
fullName: fullName,
userName: username)
}
func createUser(email: String, password: String, fullName: String, userName: String) {
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
//Handle error
if let error = error {
print("DEBUG: Failed to create user with error: ", error.localizedDescription)
return
}
guard let profileImg = self.plusPhotoBtn.imageView?.image else { return }
guard let uploadData = profileImg.jpegData(compressionQuality: 0.3) else { return }
let userID = Auth.auth().currentUser!.uid
let filename = NSUUID().uuidString
//Storage location for photo in Firebase
let storageRef = Storage.storage().reference().child("profile_images").child(userID).child(filename)
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
//Handle error
if let error = error {
print("Failed to upload image to Firebase Storage with error", error.localizedDescription)
return
}
guard metadata != nil else { return }
let path = storageRef.fullPath;
guard let username = self.usernameTextField.text?.lowercased() else { return }
storageRef.downloadURL { (url, _) in
let data = ["name": fullName,
"username": username,
"profileImagePath": path,
"email" : email] as [String : Any]
self.addDocument(userData: data)
}
})
}
}
I think you should add the "downloadURL" part inside the "putData".
After completion of the put data process you should try to get the URL or else it will fail.
Try this and see if it works:
#objc func handleSignUp() {
//Signup properties
guard let email = email.text else { return }
guard let password = password.text else { return }
guard let fullName = name.text else { return }
guard let username = name.text?.lowercased() else { return }
createUser(email: email,
password: password,
fullName: fullName,
userName: username)
}
func createUser(email: String, password: String, fullName: String, userName: String) {
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
//Handle error
if let error = error {
print("DEBUG: Failed to create user with error: ", error.localizedDescription)
return
}
guard let profileImg = self.plusPhotoBtn.imageView?.image else { return }
guard let uploadData = profileImg.jpegData(compressionQuality: 0.3) else { return }
let filename = NSUUID().uuidString
//Storage location for photo in Firebase
let storageRef = Storage.storage().reference().child("profile_images").child(filename)
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
//Handle error
if let error = error {
print("Failed to upload image to Firebase Storage with error", error.localizedDescription)
return
}
guard let metadata = metadata else { return }
guard let username = self.usernameTextField.text?.lowercased() else { return }
storageRef.downloadURL { (url, _) in
guard let downloadURL = url else {
print("DEBUG: Profile image url is nil")
return
}
let data = ["name": fullName,
"username": username,
"profileImageUrl": downloadURL,
"email" : email]
self.addDocument(userData: data)
}
})
}
}
func addDocument(userData: [String: Any]) {
Firestore.firestore().collection("profile_data").addDocument(data: userData) { (err) in
if let err = err {
debugPrint("Error adding document: \(err)")
} else {
self.navigationController?.popViewController(animated: true)
}
}
}

how to save username and email to firebase

i have watched some tutorial about save user info to DataBase after register or SignUp in the app but the problem that he save all the users by there uid and what i want is to save the users by there usernames what do you think is the professional or the better way to do that or it doesn't matter to chat app
#IBAction func SignUp(_ sender: Any) {
if username.text != nil, email.text != nil, password.text != nil, fullname.text != nil {
activityIndicator.startAnimating()
Auth.auth().createUser(withEmail: email.text!, password: password.text!, completion: { (user, error) in
if error != nil {
AlertController.showAlert(self, titel: "Error", message:".Fill all fields\n .User do exists\n .Network error ")
self.activityIndicator.stopAnimating()
return
}
let uid = user?.uid
let storageRef = Storage.storage().reference(forURL: "gs://,,,,,,,,,.com").child("profile_image").child(uid!)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1){
storageRef.putData( imageData, metadata: nil, completion: { (metadata, error) in
if error != nil{
return
}
let profileImageUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let usersReferance = ref.child("users")
let newUserReferance = usersReferance.child(uid!)
newUserReferance.setValue(["fullname": self.fullname.text, "username": self.username.text, "email": self.email.text, "password": self.password.text, "profileImageUrl": profileImageUrl])
})
}
self.dismiss(animated: true, completion: nil)
self.activityIndicator.stopAnimating()
})
}
}
}
if you want to save the users by their username yes you can do as follow
#IBAction func SignUp(_ sender: Any) {
if username.text != "", email.text != "", password.text != "", fullname.text != "" {
activityIndicator.startAnimating()
Auth.auth().createUser(withEmail: email.text!, password: password.text!, completion: { (user, error) in
if error != nil {
AlertController.showAlert(self, titel: "Error", message:".Fill all fields\n .User do exists\n .Network error ")
self.activityIndicator.stopAnimating()
return
}
let uid = user?.uid // here you are providing userID
let storageRef = Storage.storage().reference(forURL: "gs://.........com").child("profile_image").child(uid!)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1){
storageRef.putData( imageData, metadata: nil, completion: { (metadata, error) in
if error != nil{
return
}
let profileImageUrl = metadata?.downloadURL()?.absoluteString
let ref = Database.database().reference()
let usersReferance = ref.child("users")
// let newUserReferance = usersReferance.child(uid!) //here in ref you are creating a node with UID
//use your username
let newUserReferance = usersReferance.child(username.text!)
//set child values here as you doing
newUserReferance.setValue(["fullname": self.fullname.text, "username": self.username.text, "email": self.email.text, "password": self.password.text, "profileImageUrl": profileImageUrl])
})
}
self.dismiss(animated: true, completion: nil)
self.activityIndicator.stopAnimating()
})
}
}
For 2 . 1) I do not think it will be a bette approach as if you set node with username if while signUp other user filled same username data will be replaced with new data
2) if you use some checks that username is valid or not it will work , but just for concern need a additional reference in database for it to check username is available or not
-- Do as check in whole database that username is taken or not
-- or make a node with list of usernames and and get all those in array and check offline for a fast response with textfield validations or can even put observe event

Facebook Login Showing Twice

Facebook Login screen showing twice, the first one is the regular login page, but the second says "you have already authorized my app name". Can anyone tell me what I'm doing wrong in my code.
Here is my login code:
static func createAndLogin(_ viewController: UIViewController, completion: #escaping (_ success: Bool) -> Void) {
let loginManager = FBSDKLoginManager()
loginManager.logOut()
loginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends"], from: viewController) { (result, error) -> Void in
if error != nil {
print("login FAILED \(error)")
completion(false)
} else if (result?.isCancelled)!{
print("login is CANCELLED")
completion(false)
} else if FBSDKAccessToken.current() != nil {
let accessToken = FBSDKAccessToken.current().tokenString
let credential = FIRFacebookAuthProvider.credential(withAccessToken: accessToken!)
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if error != nil {
print("SIGN IN WITH FIREBASE FAILED")
completion(false)
} else {
print("YAY LOGIN SUCCESSFULL!!!!")
if let mainUser = FIRAuth.auth()?.currentUser?.providerData{
for profile in mainUser {
let providerID = profile.providerID
let uid = profile.uid // provider-specific UID
let name = profile.displayName
let email = profile.email
let photoUrl = profile.photoURL
if (FBSDKAccessToken.current() != nil) {
let facebookRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, gender, first_name, last_name, middle_name, picture"])
facebookRequest?.start(completionHandler: { (connection, result, error) in
if error == nil {
print(result as Any)
let data = result as! NSDictionary
let gender = data.object(forKey: "gender") as! String
var newUser = User(firstName: name!, profileImageURL: ("\(photoUrl!)"), gender: gender)
newUser.save()
self.currentUserID = uid
}
})
}
completion(true)
}
}
}
})
}
}
}
That to be expected with the default login behavior. You might want to try setting loginManager.loginBehavior = .systemAccount for a smoother login experience. That will try to login with the FB credentials you gave apple in settings, which won't require switching apps at all. If the user isn't logged into FB in settings, then it'll fall back to one of the other more intrusive methods(webivew or FB app).

How to write registered user into database in Swift?

When i select register.. the data is sent to Firebase authentication but does not store in the database? Can anyone tell me where im going wrong?
func handleRegister(){
// Validation
guard let email = emailTextField.text, let password = PassTextField.text, let name = nameTextField.text
else{
print("Please provide an Email and Password")
return
}
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
if error != nil {
print(error!)
return
}
// Successfully authenticated user
// Saving Data to the Database
let ref = FIRDatabase.database().reference(fromURL: "https://chat-47e5b.firebaseio.com/")
let values = ["name": name, "email": email]
ref.updateChildValues(values, withCompletionBlock: { (err,ref)
in
if err != nil {
print(err!)
return
}
print("Saved user successfully into Firebase")
})
})
}
You are not doing it right, you should first get a reference to the db:
self.ref = FIRDatabase.database().reference()
Then:
let values = ["name": name, "email": email]
self.ref.child("users").child(user.uid).setValue(values)
As a side note, convert this:
if error != nil {
print(error!)
return
}
To this:
guard let error = error else {
print(error)
return
}

Resources