![]()
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.






