Search code examples
iosswiftwebsocketgetstream-io

Stream chat: websocket disconnected, chat list not updating on reconnect


Experimenting with Stream's chat service, and we're considering to migrate to it for our iOS app. I'm using version 2.6.2 of their SDK for iOS. I'm getting this error sometimes when the websocket disconnects though: Websocketprovidererror The image is in Norwegian, but in English it says: The action couldn't be completed (STREAMCHATCLIENT.WEBSOCKETPROVIDERERROR-bug 1). The list of chats in the ChannelsViewController is purged as part of cleaning the state after a disconnect as is evident in the logs:

[14 Jan 09:36:55.487] [DEBUG] Clearing state after disconnect...
[14 Jan 09:36:55.487] [DEBUG] Cancelling background work...
[14 Jan 09:36:55.489] [DEBUG] :purple_heart: Background mode off
[14 Jan 09:36:55.489] [DEBUG] Disconnecting: Processing finished in background
[14 Jan 09:36:55.491] [DEBUG] Parsing WebSocket disconnect... (error: Cancelled)
[14 Jan 09:36:55.492] [DEBUG] Clearing state after disconnect...
[14 Jan 09:36:55.492] [DEBUG] Cancelling background work...
[14 Jan 09:36:55.492] [ERROR] :x: :broken_heart::rage: Disconnected by error WebSocketProviderError(reason: "Cancelled", code: -1, providerType: StreamChatClient.StarscreamWebSocketProvider, providerError: nil) in websocketDidDisconnect(error:)[304]

The problem is that even though the websocket reconnects shortly, the chat list in the UI is never updated.

How do I prevent errors like these just popping up randomly in the UI, and how do I make sure that the list of chats in the UI is updated after the websocket has reconnected?


Solution

  • It seems that setting the user with Client.shared.set(user:token) multiple times might cause problems. Make sure you don't set a user that has been set already. The error still happens a few times, but not as mugh anymore. I added this check:

    guard Client.shared.user.role == .anonymous else {
            log("User is already logged in. Aborting chat login process")
            return
        }
    

    Make note that this check will fail if someone logs in after logging out and the user hasn't been reset properly on logout. In the documentation it says that to log out you have to run Client.shared.disconnect(), but you also have to reset the user with Client.shared.setAnonymousUser(). The ID and everything of the previous user will be removed too.