Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Server-Sent Events on IOS using Firebase?

I am trying to listen the firebase events using rest api.The problem is the callback method is not called. I am using EventSource for this purpose.Is this the correct way to listen the events?

Auth.auth().currentUser?.getIDTokenForcingRefresh(true, completion: { (token, error) in
    let server : String =  "https://project-XXXXX.firebaseio.com/.json?auth=\(token!)"

    let eventSource: EventSource = EventSource(url: server)
    eventSource.onOpen {
        // When opened
        debugPrint("eventSource open")
    }

    eventSource.onError { (error) in
        // When errors
        debugPrint("error = \(error?.localizedDescription)")
    }
    eventSource.onMessage { (id, event, data) in
        debugPrint("data = \(data)")
        // Here you get an event without event name!
    }

    eventSource.addEventListener("child_added") { (id, event, data) in
        debugPrint("data = \(data)")
        // Here you get an event 'event-name'
    }
})
like image 772
sant05 Avatar asked Oct 29 '22 22:10

sant05


1 Answers

I finally found the answer. I have to add 'put' event listener instead of 'child_added' event listener. According to documentation, we can use only following event listener:

  • put
  • patch
  • keep-alive
  • cancel
  • auth_revoked

(Reference: https://github.com/inaka/EventSource/issues/86#issuecomment-354029202 )

like image 69
sant05 Avatar answered Nov 15 '22 07:11

sant05