所以问题似乎出在我的profileViewController上。在完成此代码段的注册后,我设置了当前用户。

class func setCurrent(_ user: User, writeToUserDefaults: Bool = true) {
        print(user)
        print("")
        if writeToUserDefaults {
            let data = NSKeyedArchiver.archivedData(withRootObject: user)

            UserDefaults.standard.set(data, forKey: "currentUser")
            UserDefaults.standard.synchronize()
        }
        _current = user
        print(_current)
    }


然后在那之后,它将转到我的profileViewController并尝试寻找原来为空的用户。为什么在我什至没有去视图控制器之前就去那里。为什么没有?
以下是我的个人资料视图控制器和我的viewDidLoad

 class ProfileeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
        var profileHandle: DatabaseHandle = 0
        var profileRef: DatabaseReference?
        let cellID = "cellID"
        let profileSetupTransition = AlterProfileViewController()
        let settingView = SettingsViewController()
        var userEvents = [Event]()
        var userId: String?
        var user: User?
        var emptyLabel: UILabel?

        var currentUserName: String = ""


        override func viewDidLoad() {
            super.viewDidLoad()
            collectionView?.backgroundColor = UIColor.white
            let user = self.user ?? User.current

            profileHandle = UserService.observeProfile(for: user) { [unowned self](ref, user, events) in
                self.profileRef = ref
                self.user = user
                self.userEvents = events
                // self.jobs = allJobs
                // self.reciepts = allReciepts

                // print(self.userEvents)
                //  print(self.reciepts)
                DispatchQueue.main.async {
                    self.collectionView?.reloadData()
                }

            }


我调用setCurrent的方法如下

   // will handle the  sign up of a user
    @objc func handleSignUp(){
        // first we cant to take sure that all of the fields are filled
        var profilePic: String = ""
        // will take the user selected image and load it to firebase
        let imageName = NSUUID().uuidString
        guard let username = self.nameTextField.text,
            let confirmPassword = self.confirmPasswordTextField.text,
            let email = self.emailTextField.text,
            let password = self.passwordTextField.text,
            !username.isEmpty,
            !email.isEmpty,
            !password.isEmpty,
            !confirmPassword.isEmpty
            else {
                print("Required fields are not all filled!")
                return
        }
        if self.validateEmail(enteredEmail:email) != true{
            let alertController = UIAlertController(title: "Error", message: "Please Enter A Valid Email", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        }
        // will make sure user is validated before it even tries to create user
        // will make sure the password and confirm password textfields have the same value if so it will print an error
        if self.passwordTextField.text != self.confirmPasswordTextField.text {
            let alertController = UIAlertController(title: "Error", message: "Passwords Don't Match", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        }
        //create a reference to the sotrage database in firebase
        let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).PNG")
        //following function does the work of putting it into firebase
        //notice I also set the value of profilepic oo it can be saved in the updated user instance in the database
        if let userImage = selectedImageFromPicker,let uploadData = UIImageJPEGRepresentation(userImage, 0.1){
            AuthService.createUser(controller: self, email: email, password: password) { (authUser) in
                guard let firUser = authUser else{
                    return
                }
                storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print(error ?? "")
                        return
                    }
                    profilePic = (metadata?.downloadURL()!.absoluteString)!
                    //printing to make sure values are contained in these strings
                    print(profilePic)
                    print(username)

                    UserService.create(firUser, username: username, profilePic: profilePic, location: self.userLocation!, completion: { (user) in
                        guard let user = user else {
                            print("User not loaded into firebase db")
                            return
                        }
                        User.setCurrent(user, writeToUserDefaults: true)
                        // will set the current user for userdefaults to work
                        print(user.profilePic ?? "")
                        print(user.username ?? "")

                        // self.delegate?.finishSigningUp()
                        self.finishSigningUp()

                    })
                })
            }
        }
    }


然后调用此方法将用户移至homeviewController并将其设置为root

func finishSigningUp() {
    print("Finish signing up from signup view controller")
    print("Attempting to return to root view controller")
    let homeController = HomeViewController()
    //should change the root view controller to the homecontroller when done signing up
    self.view.window?.rootViewController = homeController
    self.view.window?.makeKeyAndVisible()
}

最佳答案

当您执行User.current时,将使用用户默认值检索先前保存在该用户默认值上的当前用户,该用户在setCurrent方法上正确吗?

您是否使用键“ currentUser”检查用户是否正确保存在用户默认设置上?也许这就是为什么它为零。

为什么我什至没有去viewcontroller之前就去那里?也许您正在执行某种异步方法计算,即使尚未完成,您也要转到vie控制器。在没有异步方法的结果的情况下,您将其移至该逻辑,并且逻辑上是您的值为零,因为您不希望设置它们。当我看到您的代码片段并且您在代码流中调用了一些异步方法时,这就是一个假设。

关于ios - Controller 在应用程序进入之前就已初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47117715/

10-11 00:05