Integrate Firebase in iOS

  1. Go to the Firebase console and create a new project.

  2. Click on "Add Firebase to your iOS app", you will see some steps. a) The first step is to add your iOS app's bundle id. b) A GoogleService-Info.plist file will be downloaded. Add this file in your Xcode project. Add Python to PATH c) If you do not have pods install in your project you need to install them. d) Last step is to add the initializing code in your App Delegate and click Finsh.


import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool {
FIRApp.configure()
return true
}
}

3) Add following pods in your Podfile.


pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Auth'

To add Facebook authentication in Firebase

  1. Click on Authenticate on the left side of your Firebase App.
  2. Click on Sign-in Method and enable Facebook by providing Facebook App ID and Facebook Secret Key.

Add Python to PATH

Structuring Data in Firebase

Here we cover the best practices to structure the JSON data in our Firebase Realtime Database. basically the data in Firebase is structure as a JSON tree.

Add Python to PATH

Here we have created three tables in our Firebase Realtime database First is for all the books. Second is for the all Genre. Third is for all the users.

As you can see that we have divided the Main table into smaller table because Firebase allows nesting of data to only 32 levels deep. Also we gives access to user to read and write a data in Firebase database from iOS App we give him access to all the data under the node, so it is best to keep the table as small as possible and avoid nesting.

If data is separated into small table it can be downloaded in separate server calls as per the requirement.

Also to maintain relation between data of two diffrent tables add the "key" of one table data into other. In this way we have to maintain a two-way relationship betweent the tables.

Add Python to PATH

Here we have maintain the relation between all_books/genres and all_genres/action by keeping the genres/action with key "action" in "all_books/extreme_honor" table, and keeping the book key i.e "extreme_honor" in "all_genres/action/books". By this way we can query in table to get only those books with genre "Action".

Some Commonly Used Firebase syntax

To authenticate in Firebase


FIRAuth.auth()?.signInWithCredential(credential, completion:
{ (user, error) -> Void in
if(error != nil){
print("error \(error)" )
}else{

let userId: String = (FIRAuth.auth()?.currentUser?.uid)!
print("userID \(userId)")


}
})

Read and Write in Firebase

Write data in Firebase


let ref = FIRDatabase.database().reference()
let usersRef = ref.childByAppendingPath("users")
let userRef = usersRef.childByAppendingPath(userId)
let userInfo: AnyObject = ["user_email": "[email protected]","userGender": "Male", "userName": "XYZ"]
userRef.setValue(userInfo)

Read data from Firebase


let userID = FIRAuth.auth()?.currentUser?.uid
ref.child("users").child(userID!).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 \(error.localizedDescription)")
}

Query in Firebase

Here we make query to find all the favorite books of a particular user.


let allUsersRef = ref.child("users")
let userRef = allUsersRef.child(userId)
let favBooks = userRef.child("isFavoriteBook")

let  booksRef = ref.child("all_books")

booksRef.queryOrderedByChild("isFavorite/\(userId)").queryEqualToValue(true)
.observeEventType(.ChildAdded, withBlock: { snapshot in
print("snapSHot ==== \(snapshot)")

let booksItem = Books(snapshot: snapshot )

bookArray.append(booksItem)
completion(true, bookArray)
})

results matching ""

    No results matching ""