Firebase RealTime Database Example Project in iOS - Swift 4 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

1 Oct 2017

Firebase RealTime Database Example Project in iOS - Swift 4

Data is stored as JSON and synchronized in realtime to every connected client devices. The Firebase RealTime Database is a cloud-hosted database.

Firebase RealTime Database Example Project in iOS - Swift 4

Data is persisted locally, and even while offline, realtime events continue to fire, giving the end user a responsive experience.

Here we need to structure data, so that inserting and fetching will be done easily. Because the Firebase RealTime Database allows nesting data up to 32 levels deep, you might be tempted to think that this should be the default structure.

Best practices for data structure

Before getting in to Sample Project, Integrate your project with Firebase.

Add the following dependency to podfile:
pod 'Firebase/Database'

Run pod install and open the created .xcworkspace file.

Configure Firebase Database Rules:

The RealTime Database provides a set rules so that data can structure according to the rules.

By default, only authenticated users can access to the RealTime Database for performing read and write operations.

There are different authenticated methods choose any one of them.

Authenticate with Firebase using Facebook Login

Firebase Authentication using Email & Password

Authenticate with Firebase Anonymously on iOS

In this project we are going to start without setting up Authentication, you can configure your rules for public access.

Go to Firebase console -> Database -> Rules

Add the following rule and publish:
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Go to Firebase console -> Database -> Rules

Set up Firebase Realtime Database :

We need to initialize Firebase.

First import the Firebase SDK in AppDelegate.swift file:
import Firebase

Then, in the application:didFinishLaunchingWithOptions: method, initialize the FirebaseApp object:
// Use Firebase library to configure APIs
FirebaseApp.configure()

Once you've initialized Firebase Realtime Database, define and create a reference to your database as follows:

Open ViewController.swift file add the following code inside viewDidLoad() method:
var ref: DatabaseReference!

ref = Database.database().reference()

Writing Data:

Here we can show basic write operations.

Pass types that correspond to the available JSON types as follows:
  •     NSString
  •     NSNumber
  •     NSDictionary
  •     NSArray
For instance, we can add a username by using 'setValue' as follow:
ref.child("users").setValue(["username": "Jhon"])

Build and Run, It runs successfully. Open Firebase console we can see the users dictionary with username as John.

Open Firebase console we can see the users dictionary

Reading Data By Listening :

The FIRDataEventTypeValue event is fired every time data is changed at the specified database reference, including changes to children. To limit the size of your snapshots, attach only at the highest level needed for watching changes. For example, attaching a listener to the root of your database is not recommended.

Add the following method and call in ViewDidLoad() method:
func readData() {
    let userRef = Database.database().reference().child("users")
    let refHandle : DatabaseHandle!
    refHandle = userRef.observe(.value, with: { (snapshot) in
        let userDict = snapshot.value as? [String : AnyObject] ?? [:]
        print(userDict)
        // ...
    })
}

Build and Run, we see an output in Xcode console.

Next for testing realtime go to firebase console and change the name from 'Jhon' to 'Snow'. We can see the log in Xcode console without sending any new request.

For removing the observer add the following code.
if let handle = refHandle {
    Database.database().reference().removeObserver(withHandle: handle)
}

SingleEvent Observer:

let userID = Auth.auth().currentUser?.uid
ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User.init(username: username)

  // ...
  }) { (error) in
    print(error.localizedDescription)
}

The above observer will call only one time. Here no need to remove observer, it will be removed automatically after single request.

No comments:

Post a Comment

Post Top Ad