Lawris Lawris - 3 months ago 17
iOS Question

Event listener on Alamofire

I used to build my app on Firebase before and there was a method which listens for value updates, something like this:

refHandle = postRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let postDict = snapshot.value as! [String : AnyObject]
// ...
})


Now I'm not using firebase anymore, I'm using deployd and I use Alamofire to retrieve data in JSON. I wonder if there is an event listener in Alamofire that can execute code if the value is changing in the database, instead of retrieving the value every 2 minutes.

Thanks.

Answer

Okay so I found this thing called TRVSEventSource which is meant for handling SSE events.

So I added the following code after adding the header files and bridging them like this:

let configs = NSURLSessionConfiguration.defaultSessionConfiguration()
    configs.HTTPAdditionalHeaders = ["Accept" : "text/event-stream"]

    let eventsource = TRVSEventSource(URL: NSURL(string: "https://app.firebaseio.com/about.json?auth=<Your Database Secret>"), sessionConfiguration: configs)
    eventsource.delegate = self

    eventsource.open()

After that using the TRVSEventSourceDelegate, I added this delegate to get the information:

 func eventSource(eventSource: TRVSEventSource!, didReceiveEvent event: TRVSServerSentEvent!) {
    do{
        let data = try NSJSONSerialization.JSONObjectWithData(event.data, options: .MutableContainers)
        print(data)
    }
    catch let error
    {
        print(error)
    }
}

The following prints something like this { data = { desc = "My Data"; }; path = "/"; }

And with that also tells you within what path of the JSOn file has been edited or added, idk how to handle things separately and stuff but I think you can handle the rest XD. Not a good answer but I hope I helped XD (First time properly answering something)