MakeSchool-Tutorials / Makestagram-Swift-V3

14 stars 7 forks source link

12. Keeping Users Logged In #21

Closed chuckySF closed 7 years ago

chuckySF commented 7 years ago

I'm not sure if this was changed recently, but my UserService.create function uses firUser as a parameter. Therefore the current code displayed on the page breaks:

UserService.create(user, username: username) { (user) in
        guard let user = user else {
            // handle error
            return
        }

        User.setCurrent(user, writeToUserDefaults: true)

        let initialViewController = UIStoryboard.initialViewController(for: .main)
        self.view.window?.rootViewController = initialViewController
        self.view.window?.makeKeyAndVisible()
    }
ocwang commented 7 years ago

Everything looks correct, could you clarify what's breaking and why? Does your CreateUsernameViewController.nextButtonTapped(_:) match the following?

@IBAction func nextButtonTapped(_ sender: UIButton) {
    guard let firUser = Auth.auth().currentUser,
        let username = usernameTextField.text,
        !username.isEmpty else { return }

    UserService.create(user, username: username) { (user) in
        guard let user = user else {
            // handle error
            return
        }

        User.setCurrent(user, writeToUserDefaults: true)

        let initialViewController = UIStoryboard.initialViewController(for: .main)
        self.view.window?.rootViewController = initialViewController
        self.view.window?.makeKeyAndVisible()
    }
}
chuckySF commented 7 years ago

This is the error: Cannot convert value of type 'user.Type' to expected argument type 'FIRUser' (aka 'User')

I guess it's because my UserService.create func is expecting a "firUser" instead of "user". In my UserService.swift file, I have the function (see bottom) copied from a previous section. In order to fix the error, in my CreateUsernameViewController.swift file, I had to change this line:

UserService.create(user, username: username) { (user) in

to this line:

UserService.create(firUser, username: username) { (user) in

    static func create(_ firUser: FIRUser, username: String, completion: @escaping (User?) -> Void) {
        let userAttrs = ["username": username]

        let ref = Database.database().reference().child("users").child(firUser.uid)
        ref.setValue(userAttrs) { (error, ref) in
            if let error = error {
                assertionFailure(error.localizedDescription)
                return completion(nil)
            }

            ref.observeSingleEvent(of: .value, with: { (snapshot) in
                let user = User(snapshot: snapshot)
                completion(user)
            })
        }
    }
chuckySF commented 7 years ago

ps. i just edited my comment, i accidentally reversed the lines i was referencing.

ocwang commented 7 years ago

Got it!