【问题标题】:User variable is nil when creating a user with Firebase使用 Firebase 创建用户时,用户变量为零
【发布时间】:2019-10-04 07:45:10
【问题描述】:

我正在学习教程,但似乎无法将我的用户注册为 Firebase 中的用户变量。createUser 方法似乎为零。因此,当我打开它时,我得到一个错误。

我已经阅读了很多文档并检查了许多与我类似的其他问题,但似乎没有任何效果

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

我得到的错误是“let userID = (user?.user.uid)!”之一。这是

线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

【问题讨论】:

  • 你有没有试过检查错误对象是否不为零(在Auth.auth()...完成块内)?您对该块没有错误处理..
  • 我不使用 firebase,但您创建的用户使用与已成功登录的相同电子邮件和密码是否有意义?电子邮件不会已经被使用,因此createUser 应该返回一个错误,说明电子邮件已经注册?
  • 谢谢。我又在正确的轨道上。 :)
  • 不,如果没有匹配的帐户,则会出现错误,并且第二个代码块将运行,因此让他们注册。如果存在帐户,则没有问题。再次感谢

标签: ios swift firebase authentication firebase-authentication


【解决方案1】:

createUser(withEmail:,password:) 的完成块被调用 either a AuthResult.user an error。这就是为什么,正如 Joshua 所说,您应该在访问任何用户属性之前检查 error 是否为 nil

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多