如何使用Firebase在IOS上实现Server-Sent Events?

时间:2017-12-11 12:32:42

标签: ios firebase firebase-realtime-database server-sent-events eventsource

我正在尝试使用rest api监听firebase事件。问题是没有调用回调方法。我正在使用EventSource来实现此目的。这是听这些事件的正确方法吗?

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'
    }
})

1 个答案:

答案 0 :(得分:0)

我终于找到了答案。我必须添加'put'事件监听器而不是'child_added'事件监听器。根据{{​​3}},我们只能使用以下事件监听器:

  • 补丁
  • 保活
  • 取消
  • auth_revoked

(参考:documentation