brkr brkr - 6 months ago 247
Swift Question

How to use FIRApp.createUserWithEmail in specific database reference?

Iv been converting my post Firebase 2 codebase to Firebase 3 and having some troubles.

So basically Im trying to figure out how I create a new user at a specific location on my Firebase DB.

Goal - I want to save all new users @

var _USER_REF = FIRDatabaseReference().child("\(BASE_URL)/users")


Here is the code so far.

class DataService {

static let dataService = DataService()

let BASE_URL = "https://project-1321.firebaseio.com"
var _BASE_REF = FIRDatabaseReference().child(BASE_URL)
var _USER_REF = FIRDatabaseReference().child("\(BASE_URL)/users")
var _NEWS_REF = FIRDatabaseReference().child("\(BASE_URL)/news")
var _MARKET_STATS = FIRDatabaseReference().child("\(BASE_URL)/market")

var CURRENT_USER_REF: FIRDatabaseReference {

let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String
let currentUser = FIRDatabaseReference().child("\(_BASE_REF)").child("users").child(userID)
//let currentUser = Firebase(url: "\(BASE_REF)").childByAppendingPath("users").childByAppendingPath(userID)
return currentUser

}



func createNewAccount(uid: String, user: Dictionary<String, String>) {
_USER_REF.child(uid).setValue(user)
}



}

View Controller

@IBAction func registerAccount(sender: AnyObject) {

guard let email = self.emailRegField.text where !self.emailRegField.text!.isEmpty else {
return
}

guard let username = self.usernameRegField.text where !self.usernameRegField.text!.isEmpty else {
return
}

guard let password = self.passwordRegField.text where !self.passwordRegField.text!.isEmpty else {
return
}

FIRAuth.auth()?.createUserWithEmail(email, password: password) {
(user, error) in

if error != nil {
print(error)
self.signUpErrorAlert("Alert", message: "There was a problem signing up!")
} else {

let user = ["provider": user?.providerID, "email": email, "username": username]

DataService.createNewAccount(user) // Doesnt Work

}



//Store UID in NSDefaults so if user reopen app they automatically log in if UID exsisits.
NSUserDefaults.standardUserDefaults().setValue(result ["uid"], forKey: "uid")

// Segue New User

self.performSegueWithIdentifier("newUserSegue", sender: nil)

}


// Loggin in a User who already has UID Saved to NSDefaults

When a user log's in or Registers I plan to save their "UID" to NSDefaults.

Then check like so :

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil {
self.performSegueWithIdentifier("newUserSegue", sender: nil)
} else {
print("User is not registered or has their UID saved to NSDefaults")
}

}


Is this a safe method?

Answer

@brkr In response to your comment above, you can still use the UIDs in order to add unique users to your Firebase database.

For example, here is your users ref (in the DataService Class): let REF_USERS = FIRDatabase.database().referenceFromURL("\(URL_BASE)/users")

Now, create a user in Firebase 3.0:

FIRAuth.auth()!.createUserWithEmail(email, password: pwd, completion: { authData, error  in
            if error == nil {    
                // Log user in
                FIRAuth.auth()?.signInWithEmail(email, password: pwd) { authData, error in
                    // Save user information to Firebase data
                    let user = // your user Dictionary 
                    DataService.createNewAccount(authData!.uid, user: user)
                }
            } else {
                // Handle login error here
            }
        })

The code for the create account method:

func createNewAccount(uid: String, user: Dictionary<String, String>) {
    REF_USERS.child(uid).setValue(user)
}
Comments