当前用户未设置?

时间:2017-10-27 01:48:34

标签: ios swift firebase

所以我的代码存在问题。我的注册页面抓取用户数据。它获取用户名,位置和个人资料照片。一切正常,似乎一切都被保存到firebase。但是,当创建帐户并且我转到用户配置文件时,一切似乎都是零。

这是我处理注册的功能。

 @objc func handleSignUp(){
        // first we cant to take sure that all of the fields are filled
        let bio: String = ""
        var profilePic: String = ""

        // will take the user selected image and load it to firebase
        let imageName = NSUUID().uuidString
 let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).PNG")
        if let userImage = selectedImageFromPicker,let uploadData = UIImageJPEGRepresentation(userImage, 0.1){

            storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil{
                    print(error ?? "")
                    return
                }
                 profilePic = (metadata?.downloadURL()!.absoluteString)!
                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)
                }

                // will authenticate a user into the authentication services with an email and passowrd
                AuthService.createUser(controller: self, email: email, password: password) { (authUser) in
                    guard let firUser = authUser else {
                        return
                    }
                    //will add user to the database
                    print(profilePic)
                    print(username)
                    UserService.create(firUser, username: username , profilePic: profilePic , bio: bio, location: self.userLocation!) { (user) in
                        guard let user = user else {
                            print("User successfully loaded into firebase db")
                            return
                        }
                        // will set the current user for userdefaults to work
                        print(user.profilePic)
                        print(user.username)

                        User.setCurrent(user, writeToUserDefaults: true)
                        // self.delegate?.finishSigningUp()

                        self.finishSigningUp()


                    }
                }

        })
        }
    }

这是我对配置文件控制器的viewdidload。当我打印出这里的用户时,一切都是零。

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

            }

这会处理到主页的转换。

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

我的家庭视图控制器控制这些throguh的导航,使用一组视图控制器控制snapcaht样式的滑动。像这样

 lazy var viewControllerList: [UIViewController] = {
        let homeFeedController = HomeFeedController()
        let navController = UINavigationController(rootViewController: homeFeedController)
//        let navController = ScrollingNavigationController(rootViewController: homeFeedController)


        let profileView = ProfileeViewController(collectionViewLayout: UICollectionViewFlowLayout())
        let profileViewNavController = UINavigationController(rootViewController: profileView)

        let searchController = EventSearchController(collectionViewLayout: UICollectionViewFlowLayout())
        let searchNavController = UINavigationController(rootViewController: searchController)

        return [searchNavController,navController,profileViewNavController]
    }()

Obseverprofile功能

// will observe the user object in the database for any changes and make sure that they are updated
    static func observeProfile(for user: User, completion: @escaping (DatabaseReference, User?, [Event]) -> Void) -> DatabaseHandle {
        // 1
        let userRef = Database.database().reference().child("users").child(user.uid)

        // 2
        return userRef.observe(.value, with: { snapshot in
            // 3
            guard let user = User(snapshot: snapshot) else {
                return completion(userRef, nil, [])
            }

          //  print(user)
            // 4
            Events(for: user, completion: { events in
                // 5
                completion(userRef, user, events)
            })
        })
    }

用户模型

import Foundation
import FirebaseDatabase.FIRDataSnapshot

class User : NSObject {

    //User variables
    let uid : String
    let username : String?
    let profilePic: String?
    var location: String?
    var isFollowed = false
    let bio: String?
    var dictValue: [String : Any] {
        return ["username" : username as Any,
                "profilePic" : profilePic as Any,
                "Bio" : bio as Any, "location": location as Any]
    }

    //Standard User init()
    init(uid: String, username: String, profilePic: String, bio: String, location: String = "") {
        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        self.bio = bio
    self.location = location
        super.init()
    }

    //User init using Firebase snapshots
    init?(snapshot: DataSnapshot) {
        guard let dict = snapshot.value as? [String : Any],
            let username = dict["username"] as? String,
            let profilePic = dict["profilePic"] as? String,
            let bio = dict["bio"] as? String,
        let location = dict["location"] as? String
            else { return nil }
        self.uid = snapshot.key
        self.location = location
        self.username = username
        self.profilePic = profilePic
        self.bio = bio
    }

    //UserDefaults
    required init?(coder aDecoder: NSCoder) {
        guard let uid = aDecoder.decodeObject(forKey: "uid") as? String,
            let username = aDecoder.decodeObject(forKey: "username") as? String,
            let profilePic = aDecoder.decodeObject(forKey: "profilePic") as? String,
            let bio = aDecoder.decodeObject(forKey: "bio") as? String,
            let location = aDecoder.decodeObject(forKey: "location") as? String
            else { return nil }

        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        self.bio = bio
        self.location = location
        super.init()
    }


    init?(key: String, postDictionary: [String : Any]) {
        //var dict : [String : Any]
        //print(postDictionary as? [String:])
        let dict = postDictionary
        print(dict)
        let profilePic = dict["profilePic"] as? String ?? ""
        let bio = dict["bio"] as? String ?? ""
        let username = dict["username"] as? String ?? ""
        let location = dict["location"] as? String ?? ""

        self.uid = key
        self.location = location
        self.profilePic = profilePic
        self.username = username
        self.bio = bio
    }


    //User singleton for currently logged user
    private static var _current: User?

    static var current: User {
        guard let currentUser = _current else {
            fatalError("Error: current user doesn't exist")
        }

        return currentUser
    }

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

extension User: NSCoding {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(username, forKey: "username")
        aCoder.encode(profilePic, forKey: "profilePic")
        aCoder.encode(bio, forKey: "bio")
        aCoder.encode(location, forKey: "location")

    }
}

0 个答案:

没有答案