使用Firebase创建用户时,用户变量为nil

时间:2019-05-17 01:51:04

标签: ios swift firebase authentication firebase-authentication

我正在按照教程进行操作,似乎无法在Firebase中将用户变量注册为用户。.createUser方法似乎为nil。因此,当我打开包装时,会出现错误。

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

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

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

  

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

1 个答案:

答案 0 :(得分:2)

使用{em> 和createUser(withEmail:,password:)AuthResult.user调用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)
  }
}