首页 > 解决方案 > 成功登录 Firebase 后尝试执行 segue

问题描述

我想在登录成功后执行 segue,否则我希望视图保留在登录屏幕上。我这样做有点麻烦。对 Swift 来说相当陌生,所以请原谅我的任何无知。非常感谢您的参与。

这是我的 LogInViewController

import UIKit
import FirebaseAuth
import Firebase

class LogInViewController: UIViewController {


let firebaseService = FirebaseService()

@IBOutlet weak var emailTextField: UITextField!

@IBOutlet weak var passwordTextField: UITextField!



override func viewDidLoad() {
    super.viewDidLoad()
}



@IBAction func logInAction(_ sender: Any) {
        firebaseService.signIn(email: emailTextField.text!, password: passwordTextField.text!)

    if Auth.auth().currentUser != nil {
        afterSuccessfulLogin()
    } else {
        print("Wrong Account Info")
    }


}

func afterSuccessfulLogin() {
    performSegue(withIdentifier: "afterLogin", sender: self)
    print("\(Auth.auth().currentUser!.displayName!) has logged in!")
}


@IBAction func unwindToLogIn(storyboard: UIStoryboardSegue){

}

}

这是我的 FirebaseCalls.swift

import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase


struct FirebaseService {

var dbRef : DatabaseReference! {
    return Database.database().reference()
}
var storageRef : StorageReference! {
    return Storage.storage().reference()
}

private func saveInfo(user: User?, username: String, password: String, city: String, state: String, bio: String) {

    //Create User Dictionary Info

    let userInfo = ["email": user?.email!, "username": username, "city": city, "state": state, "bio": bio, "uid": user?.uid, "photoUrl": String(describing: user!.photoURL!)]

    //Create User Reference

    let userRef = dbRef.child("users").child((user?.uid)!)

    // Save User Info in Database

    userRef.setValue(userInfo)

    //SIGN IN THE USER
    signIn(email: (user?.email!)!, password: password)
}

func signIn(email: String, password: String) {
    Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
        if error == nil {
            if let user = user {
                print("\(user.displayName!) has signed in successfully!")



            }
        } else {
            print(error!.localizedDescription)
        }
    })

}


private func setUserInfo(user: User?, username: String, password: String, city: String, state: String, bio: String, data: NSData!) {

    //CREATE PATH FOR USER IMAGE
    let imagePath = "profileImage\(user!.uid)/userPic.jpg"

    //CREATE IMAGE REFERANCE

    let userImageRef = storageRef.child(imagePath)

    //Create MetaData for the Image

    let metaData = StorageMetadata()
    metaData.contentType = "image/jpeg"


    userImageRef.putData(data as Data, metadata: metaData) { (metaData, error) in
        if error == nil {
            let changeRequest = user?.createProfileChangeRequest()
            changeRequest?.displayName = username
            changeRequest?.photoURL = metaData!.downloadURL()
            changeRequest?.commitChanges(completion: { (error) in
                if error == nil {
                    self.saveInfo(user: user, username: username, password: password, city: city, state: state, bio: bio)

                }else {
                    print(error!.localizedDescription)
                }
            })



        }else {
           print(error!.localizedDescription)
        }
    }

}

func resetPassword(email: String){
    Auth.auth().sendPasswordReset(withEmail: email, completion: { (error) in
        if error == nil {
            print("An email with information on how to Reset your password has been sent.")
        } else {
            print(error!.localizedDescription)
        }
    })
}


    //Save the user Image in the Firebase Storage File



func signUp(email: String, username: String, password: String, city: String, state: String, bio: String, data: NSData!) {
    Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
        if error == nil {
            self.setUserInfo(user: user, username: username, password: password, city: city, state: state, bio: bio, data: data)
        } else {
            print(error!.localizedDescription)
        }
    })
}

}

标签: iosxcodefirebasefirebase-authenticationswift4

解决方案


给这个方法添加一个补全

  func signIn(email: String, password: String,completion:@escaping(_ finished:Bool)->void) {
    Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
        if error == nil {
            if let user = user {
                print("\(user.displayName!) has signed in successfully!")

                completion(true)

            }
        } else {
            print(error!.localizedDescription)

              completion(false)
        }
    })

}

//

@IBAction func logInAction(_ sender: Any) {

    firebaseService.signIn(email: emailTextField.text!, password: passwordTextField.text! , {  (finished) in

       if finished {

             if Auth.auth().currentUser != nil {
                afterSuccessfulLogin()
             } else {
             print("Wrong Account Info")
         }

     }


})

推荐阅读