Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Register Realtime User Information at Firebase in iOS App

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 2.22k
    Comment on it

    Firebase is a realtime database where we can store the information and can check whether data got saved or not in Firebase. Here is a simple example of creating a project and connection of the project with Firebase, so, here we go.

     

     

    First of all,  go to the firebase (https://firebase.google.com/) and create a project and after creating the project with any name you will get a project id. Now click on tab ‘Add firebase to your iOS app screen’
    copy bundle identifier from Xcode project and then register your application. After registration, you will see a link to download googleservice-info.plist which later on you have to add in your project so download the plist. Now go back to the firebase and press continue button and then finish after one step here complete the application registration part. Now follow the given below steps:-


    1. Go to the authentication from side menu
    2.  setup sign-in method by enabling email/password


    Now open the terminal to install pods of Firebase in your application. Follow the given below steps:-
    1. cd project path
    2. pod init
    3. Write these lines in pod file after opening the file with Xcode
      pod 'Firebase'
      pod 'Firebase/Auth'
      pod 'Firebase/Core'
      pod 'Firebase/Database'
    4.pod install

     

     

     

     

     

     

    User interface for the application can easily be created by using two controllers and one navigation controller as given below in the screenshots:-

     

     

     

    Now we will move towards the coding part where first of all, import Firebase in AppDelegate file and configuration of Firebase application will be start from here only.

     

    //
    //  AppDelegate.swift
    //  RegisterUserDataInFireBase
    //
    //  Created by elcaptain1 on 9/21/17.
    //  Copyright  2017 Tanuja. All rights reserved.
    //
    
    import UIKit
    import Firebase
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.
             FIRApp.configure()
            return true
        }
    
        func applicationWillResignActive(_ application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        }
    
        func applicationDidEnterBackground(_ application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        }
    
        func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        }
    
        func applicationDidBecomeActive(_ application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        }
    
        func applicationWillTerminate(_ application: UIApplication) {
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }
    
    
    }

     

     

    //
    //  ViewController.swift
    //  RegisterUserDataInFireBase
    //
    //  Created by elcaptain1 on 9/21/17.
    //  Copyright  2017 Tanuja. All rights reserved.
    //
    
    import UIKit
    import Firebase
    import FirebaseAuth
    import FirebaseCore
    import FirebaseDatabase
    
    
    class ViewController: UIViewController {
        
     
        @IBOutlet weak var txtUserName: UITextField!
        
        
        @IBOutlet weak var txtEmail: UITextField!
        
        
        @IBOutlet weak var txtPassword: UITextField!
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // Do any additional setup after loading the view, typically from a nib.
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        
        
        
        @IBAction func btnRegister(_ sender: AnyObject) {
            register()
        }
        
       
        
        func register()  {
            if txtUserName.text != "" && txtEmail.text != "" && txtPassword.text != ""
            {
                
                if(Helper.helper.isValidEmail(testStr: txtEmail.text!))
                {
                    if(txtPassword.text!.characters.count>5)
                    {
                        FIRAuth.auth()?.createUser(withEmail: txtEmail.text!, password: txtPassword.text!, completion: { (user, error) in
                            if error != nil
                            {
                                print(error?.localizedDescription)
                            }
                            else
                            {
                                let uid = FIRAuth.auth()?.currentUser?.uid
                                let databaseRef = FIRDatabase.database().reference()
                                let userData : [String:Any] = ["email":self.txtEmail.text!,"uid":uid!,"username":self.txtUserName.text!]
                                databaseRef.child("users").child(uid!).setValue(userData)
                                Helper.helper.switchToNavigationVC()
                            }
                        })
                    }
                    else
                    {
                        let alert = Helper.helper.showAlert(message: "The password must be 6 characters long or more")
                        self.present(alert, animated: true, completion: nil)
                    }
                }
                else
                {
                    let alert = Helper.helper.showAlert(message: "Please enter valid email id")
                    self.present(alert, animated: true, completion: nil)
                }
                
            }
            else
            {
                let alert = Helper.helper.showAlert(message: "Please enter data in all fields")
                self.present(alert, animated: true, completion: nil)
            }
            
            
        }
    
    }

     

     

    //
    //  Helper.swift
    //  RegisterUserDataInFireBase
    //
    //  Created by elcaptain1 on 9/21/17.
    //  Copyright  2017 Tanuja. All rights reserved.
    //
    
    import Foundation
    import UIKit
    
    class Helper
    {
        static let helper = Helper()
        func switchToNavigationVC() {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "VC") as! UINavigationController
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = vc
        }
        
        func isValidEmail(testStr:String) -> Bool {
            // print("validate calendar: \(testStr)")
            let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
            
            let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            return emailTest.evaluate(with: testStr)
        }
        
        func showAlert(message:String)-> UIAlertController {
            let alert = UIAlertController(title: "RegisterUserDataInFireBase", message: message, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            return alert
        }
    }

     

    Output:-

     

     

     

     

     

    You can also download the sample code from the attached file given below, for any questions, please feel free to write in comments.

    How to Register Realtime User Information at Firebase in iOS App

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: