Real-time chat application with firebase and iOS swift client

Author - Nishita

Real time chat

Now a days trend for real-time communication gets increased, web socket brings change to messaging apps development for real-time communication and instant messaging. Firebase is pride great way for real-time chat using PubSub method. Here you will learn how to integrate iOS client app with firebase for real-time communication. It’s easy to use and store the data in firebase real-time database.

Firebase configuration

To use firebase with iOS client first we need to create an app on the firebase. Let’s create app here using firebase console. For now, we are going to create chat app for iOS client only so let’s create an iOS app and set configuration in the newly created swift project as shown in below screenshots. Here are steps to accomplish this.

– Register app

– Download GoogleService-info.plist file and set it your Xcode project.

– Add Firebase SDK, Include the following pods in your Pod file

pod ‘Firebase/Auth’

pod ‘Firebase/Database’

– Import Firebase Module in AppDelegate

– Configure firebaseApp in didFinishLaunchingWithOptions method

import Firebase FirebaseApp.configure()

– Create a new account using user’s E-mail and password

Auth.auth().createUser(withEmail: txtEmail.text!, password: txtPwd.text!) { (user, error) in

if error == nil {

// User created successfully

} else {

}

}

– Add User data in Firebase real-time Database

Auth.auth.createUser(withEmail: email, password: password) { (authResult, error) in
var ref: DatabaseReference
let full-name = [“First-name”: Firebase , “Last-name”: Demo]
self.ref.child(“users”).child((user?.uid)!).setValue([“username”: full-name])
}

Create new user with Facebook

Likewise, you can also create a user using your Facebook account. To accomplish that you have to include the following pods in your Pod file for Facebook authentication and write code as written below.

pod ‘FBSDKLoginKit’
pod ‘FacebookCore’
pod ‘FacebookLogin’ 
pod ‘Firebase/Storage’ // This will be used later while we upload and receive profile image of user

– Go https://developers.facebook.com/docs/facebook-login/ios/ and register app for Facebook authentication
–  Login User with Facebook authentication 

let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth.signInAndRetrieveData(with: credential) { (authResult, error) in
if error != nil {
return // it gives the error if present
}

Forget Password reset with E-mail

Probably, you may need an option to reset the password of your user account in any case. Hence below code will be helpful for that.

let resetEmail = forgetPasswordAlert.textField.text // AlertController E-mail Text-filled

Auth.auth.sendPasswordReset(withEmail: resetEmail!, completion: { (error) in

if error != nil

{

// Reset Failed

}

else

{

// Reset Email sent successfully

}

})

Fetch all users From Firebase database

Maybe you will need a list of online users to chat with them. Here is small code snippet for how to fetch all online users.

let ref = Database.database().reference()
ref.child(“users”).observeSingleEvent(of: .value, with: { (snapshot) in // snapshot of users database
if snapshot.exists()
{
if let userData = snapshot.value as? Dictionary<String,AnyObject> 
{
for(key, value) in userData {
if let userValue = value as? Dictionary<String,AnyObject>  // list of users
{
if(Auth.auth().currentUser!.uid != key) {.  // except current user

let dict = NSMutableDictionary()

dict.setObject(key, forKey:”firebaseId” as NSCopying) // add firebaseId of users dict.setObject((userValue[“username”] as! NSDictionary).value(forKey: “First-name”)!, forKey: “First-name” as NsCopying) self.arrUserList.add(dict) // list of users added in array

}

}}

}

self.tblUserList.reloadData() // reload tableView for display all Users

})

}

Real-time chat using Firebase : Send message to other User

This is a core part of this article how to communicate with two users of the firebase. Here is code to accomplish this.

let database = Database.database().reference()

let str =  “\(String(describing: self.getCurrentTimeStamp().replacingOccurrences(of: “.”, with: “”)))” + “_” + “\(String(describing: Auth.auth().currentUser!.uid))” + “_” + “\(String(describing: dict.object(forKey: “firebaseId”)!))”

database.child(“Chats”).child(“\(String(describing: dict.object(forKey: “firebaseId”)!))”).child(Auth.auth().currentUser!.uid).updateChildValues([str :”Message text”])

database.child(“Chats”).child(Auth.auth().currentUser!.uid).child(“\(String(describing: dict.object(forKey: “firebaseId”)!))”).updateChildValues([str : “Message text”])

Receive Message from other user

Similarly its very important to handle message sent by another user, here you will see how this is being handled easily.

let database = Database.database.reference()

database.child(“Chats”).child(Auth.auth().currentUser!.uid).child(“\(String(describing: dict.object(forKey: “firebaseId”)!))”).observe(.childAdded) { (snapshot) in   

let component = snapshot.key.component(separatedBy: “_”) // Message separated

let dictMsg = NSMutableDictionary()

dictMSg.setObject(component[1], forKey: “SenderId” as NSCopying) // set senderId

dictMSg.setObject(component[2], forKey: “ReceiverId” as NSCopying) // ReceiverId

dictMSg.setObject(snapshot.value!, forKey: “Message” as NSCopying) // Message

self.arrMsg.add(dictMsg) // Add in Array
}

// In cellForRow create 2 cells one for sender and one for receiver 

let dict1 = arrMsg.object(at: indexPath.row) as! NSDictionary

if((String(describing: dict1.objectForKey: “SenderId”)!)) == Auth.auth.currentUser?.uid {

// Sender tableView cell

cell.lblText.text =(dict1.objectForKey: “Message”) as! String

return cell
}
else {
// Receiver tableView cell

cell.lblText.text =(dict1.objectForKey: “Message”) as! String
return cell
}

Upload User Profile Picture in Firebase Store

It’s always great to provide this feature for each chat app. The user need to set their profile picture and we can easily accomplish this with firebase. Here is below code to upload an image,

var ref: DatabaseReference!

var data = NSData()

data = UIImageJPEGRepresentaion(self.imgUserProfile.image!, 0.8)! as NSData

let storageRef = Storage.storage().reference()

let filePath = “\(Auth.auth().currentUser!.uid”)/\(“imgUserProfile”)”

let metaData = StorageMetadata()

metaData.contentType = “image/jpg”

storageRef.child(filePath).putData(data as Data, metadata: metaData){(metaData, error) in

if let error = error {
// error 
return
}
}

Receive User Profile Picture From Firebase Store

It’s always great to see profile pics of other users in the list. To get profile image of each user from firebase we need to write below code:

let reference = Storage.storage().reference(forURL: “gs://messaginapp.appspot.com”)  // URL path for firebase applicaton Id

let url = reference.child(Auth.auth().currentUser!.uid).child(imageName)

let placeholderImage = UIImage(named: “placeholder.jpg”)

url.downloadURL(completion: {(url, error) in  // download image from firebase storage

if error != nil {

print(error?.localizedDescription as Any)

return

}

URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

if error != nil {

print(error as Any)

return

}

DispatchQueue.main.async {

self.imgUserProfile.image(with: url, placeholderImage: placeholderImage)  // Set download Image in imgView

}

}).resume()

})

Here you will find full source code of firebase real-time chat app for one to one chat.

Finally you have working real-time chat app using firebase as a backend.

Next you can try to add option for group chat in this project.

Thanks for reading this article.

Free SEO Checker |
Test your website for free with OnAirSEO.com

Get Your SEO report!

Don’t miss the next post!

Loading

Related Posts