Firebase Tutorial: Real-time Chat

Hi @tomelliott, great tutorial, thanks! I found in your implementation of the typing indicator that if 2+ users are chatting and the local user goes from typing to not typing, the indicator will stay displayed on their screen. This is because a ref remains for each user that has typed at least once (until they disconnect), which will be true if they are currently typing, or false if not. snapshot.childrenCount will be equal to the total number of users that have typed in that chat.

So, data.childrenCount == 1 && self.isTyping will be false, regardless of whether the local user is typing or not,

and self.showTypingIndicator = data.childrenCount > 0 will set self.showTypingIndicator to true.

Hereā€™s an alternative approach that will handle this correctly:

usersTypingQuery.observe(.value) { [weak self] (snapshot: FIRDataSnapshot) in
    guard let `self` = self else { return }
    
    DispatchQueue.global().async {
        var showTypingIndicator = false
        
        if snapshot.childrenCount > 0 {
            let enumerator = snapshot.children
            
            while let userTyping = enumerator.nextObject() as? FIRDataSnapshot {
                if userTyping.key == self.currentUser.uid { // currentUser = FIRAuth.auth()!.currentUser!.uid
                    continue
                }
                
                if userTyping.value as? Bool == true {
                    showTypingIndicator = true
                    break
                }
            }
        }
        
        DispatchQueue.main.async {
            self.showTypingIndicator = showTypingIndicator
            self.scrollToBottom(animated: true)
        }
    }
}

Great Tutorial! I am getting a lot of errors with the LoginViewController and all of the others. For Example.

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

I am getting the Error Expected Member Name Following ā€˜.ā€™

I am getting many other Issues in the ChatViewController and the ChannelListViewController and I just copied the github project is there anything I should add in the documentation that is not in the Github project.

Thanks

Hey, great tutorial!!! Everythingā€™s loud and clear. Thank you very much!

I have a question.

when it comes to picking the photolibrary image I keep getting an error.

Error Domain=NSCocoaErrorDomain Code=257 ā€œThe file ā€œIMG_0249.JPGā€ couldnā€™t be opened because you donā€™t have permission to view it.ā€

But when I use the camera it works perfect. Is anyone else getting this error ??

Hey this is a great tutorial ,Can you plz do this in Objective c.Thanks in advance.
I have been working on it last few days and still stuck ,Any help would be thankful.

I am very new to Swift and was hoping to have a functioning chat app up and running in my Xcode that I could use to further build on. Were you guys able to get this up and running without too many fixes?

Mee to have same problem with this crash error: Could any body help me?

dyld: Library not loaded: @rpath/JSQMessagesViewController.framework/JSQMessagesViewController
Referenced from: /var/containers/Bundle/Application/B3ABF229-59EC-4895-8968-52E1BD78CFFF/ChatChat.app/ChatChat
Reason: no suitable image found. Did find:
/private/var/containers/Bundle/Application/

Hi i followed this tutorial and got it working but when i create a new channel it crashes before the view changes to the chat view, i get an error of found nil while unwrapping optional extra on this line when i load it back up the channel is created.

 messageRef = channelRef!.child("messages")?

anybody have any ideas

@darkmatter I experienced this same issue and it appears to be a security issue caused by actually accessing the downloaded URL from within Firebase. To solve this problem, I simply copy the file to the temp directory of the app and pass that url to Firebase to perform the upload. After a successful upload, I delete the file. Here is my copy func in Swift 3:

func copyFileToTempDirectory(mediaFileURL: URL) -> URL? {

    let mediaData = NSData(contentsOf: mediaFileURL)

    // optionally, write the video to the temp directory
    let mediaFilePath = NSTemporaryDirectory() + mediaFileURL.lastPathComponent
    let mediaFileURL = URL(fileURLWithPath: mediaFilePath)
    let writeSuccessful = mediaData?.write(to: mediaFileURL, atomically: true)
    if let _ = writeSuccessful {
        return mediaFileURL
    }
    else {
        return nil
    }
}

Just use this and pass the returned URL to firebase for storage and youā€™re good to go!

1 Like

Hello @tomelliott

I am very new to swift and I am working on a chat application. This tutorial is perfect, but my only problem is that I need a way to log into Google instead of logging in anonymously. Is this possible and has anyone done it before?

The camera takes the picture, but does not send it. Also, is it possible to make an unread icon on channels with unread messages, or add notifications? Lastly, is it possible to change the Channel Table View Controller to a normal view controller with a table view? I can post code if that is necessary, but I havenā€™t changed much from the sample file.

Thank You,
Fin

Iā€™m having the same issues too. Concerning the squashed photo I think the collection view cell is set before the image is loaded in and once it is loaded the photo get squished inside. In my project Iā€™ve cached the images and if I pop off the chat view controller and push it back on the cells get the dimensions right. @tomelliott do you know how to resize the cell after the image is set?

Hi there! I was wondering - is there a way to implement push notifications with this firebase real-chat implementation? So that people would receive notifications when they are messaged? (For 1 to 1 messaging). Would appreciate any advice, thank you so much!

Any solution to having a custom Avatar for each user? Im trying to use the DataSource method with a FIRSnapshot of the users profile URL using SD_WebImage

ā€¦ swift - User Specific Avatar in JSQMessagesViewController with SDWebImage - Stack Overflow

ā€¦any help greatly appreciated.

Hi everyone I read Firebase Tutorial: Real-time Chat

and there are one problem

JSQMessagesViewController use var messages = JSQMessage as class

but my class contains this property:

  1. isDeletedByBroker
  2. isDeletedByUser
  3. isFromBroker
  4. msgContent
  5. type

only and I didnā€™t want to use var messages = JSQMessage as class I wanna use my custom class with the property in the before

so how to use messageDataForItemAt and how to show date with JSQMessageData because it use JSQMessage

Ok I make my class and didnā€™t wonā€™t inheriting JSQMessage class
So how to implement
MessageDataForItemAt with my own class

@tomelliott How can I add new message with this parameter

isDeletedByBroker
isDeletedByUser
isFromBroker
msgContent
type

why when I try to run it and try to create a new channel it crashes and I get
thread 1: signal SIGABRT

Hi there!
Is it possible to make like a Channel list inside the Channel list? Like for example I log in then it appears the Channel list with:
-Sports
-Games
-Food
Then I touch on Sports and it appears like:
-Soccer
-Golf
How can I do it? IĀ“m kind of new programming, Can anyone help me? Please? I have no idea how to do it!
btw thank you!
Awesome Tutorial!

Great tutorial! I did however receive this error and was wondering if you knew how to create a dynamic rule to prevent the indexing problem? Thanks!

Using an unspecified index. Consider adding ā€œ.indexOnā€: ā€œ.valueā€ at /channels/-KkPddML_tTQVexNHfe7/typingIndicator to your security rules for better performance

Hi,

after going through the Getting Started Firebase-Tutorial I turned to this Firebase tutorial. Unfortunately, I was unable to get the code running. I am using Xcode 8.2.1 and received 6 error messages that showed that some parts of the source code are deprecated in Swift 3 (e. g., unsafeAddress(:of)). When trying to solve that problem with a switch to ā€œUse Legacy Swift Language Versionā€ set to ā€œYesā€ā€¦ Xcode came up with 16 errors mainly in the UIImage+Gif part of the code.

Any idea on how to convert that interesting code to a version that can be used with Xcode 8.2 and Swift 3?

Thanks in advance
Thomas