pusher / pusher-websocket-swift

Pusher Channels websocket library for Swift
https://pusher.com/channels
MIT License
273 stars 167 forks source link

Unable to decode data coming from Pusher #405

Closed arslankaleem7229 closed 1 year ago

arslankaleem7229 commented 1 year ago

I have integrated PusherSwift in my app and its completely working except decoding of data from pusher. For example this is the code snipped

let _ = myChannel.bind(eventName: "eventName", eventCallback: { (data: Any?) -> Void in
            print("Data recieved")
            if let data = data as? [String : AnyObject] {
                print("Data Decoded")
            }
        })

This is the code snippet so now when I trigger the event it prints "Data recieved" but not "Data Decoded". In simple words if let data = data as? [String : AnyObject] returning false

choulepoka commented 1 year ago

@arslankaleem7229

We side-stepped this issue by using a different method signature:

func bind(eventName: String, eventCallback: @escaping (PusherEvent) -> Void) -> String

This allows us to bind an event on a channel, and use Decodable (or JSONSerialization) directly:

 let myChannel = pusher.subscribeToChannel(withName: channelName)
 myChannel.bind(eventName: eventName, eventCallback: { event in

   guard let data = event.data?.data(using: .utf8) else {
     return
   }

   ... decoding the json here
})
arslankaleem7229 commented 1 year ago

Thanks @choulepoka . BTW I have used this thing to make my function work

let _ = channel.bind(eventName: "TestEvent", eventCallback: { (data: Any?) -> Void in
                if let data = data as? PusherEvent{
                    print(data[message])
                }
            })