Chat UIKit SwiftUI v3
Chat UIKit SwiftUI
Chat UIKit
SwiftUI
Version 3

Authentication

Copy link

In order to use the features of Sendbird Chat SwiftUI in your client apps, a SendbirdUI instance must be initiated in each client app through user authentication with the Sendbird server. The instance communicates and interacts with the server using an authenticated user account, and is allowed to use the SwiftUI's features. This page explains how to authenticate your user with the server.


Set an access token

Copy link

The Sendbird server authenticates requests from client apps through two methods: One is using only user ID, the other is using a user ID along with the user's access token.

The user ID authentication can be useful for applications in development or existing services where additional security is not necessarily needed. On the other hand, the access token authentication generates access tokens for each user through Chat Platform API. Once you request and obtain a token for a user, you need to use that specific access token to authenticate the user.

SBUGlobals.accessToken = {ACCESS_TOKEN}

Connect to Sendbird server

Copy link

The SendbirdUI.connect() method connects a user to the Sendbird server using the preset information of the currentUser. If the user ID used during the connection attempt doesn't exist on our server, a new user account is created with the specified user ID. The SendbirdUI.connect() method also automatically updates the user profile on the Sendbird server.

When the Sendbird View is called in SwiftUI, the connection is automatically made with the currentUser which should be already set in the SBUGlobals.

With local caching added to Sendbird Chat SDK, the latest user instance may be returned through the callback even when the user is offline. The local caching functionality stores message and channel data in the local storage and Sendbird server. As a result, even when a user is not connected to the server, the user information stored in the local cache is returned through the callback along with an error indicating the offline status.

Refer to the code below to see how to connect a user to Sendbird server:

SendbirdUI.connect { (user, error) in
    guard let user = user else {
        // The user is offline and you can't access any user information stored in the local cache.
        return
    }
    if let error = error {
        // The user is offline but you can access user information stored in the local cache.
    }
    else {
        // The user is online and connected to the server.
    }
}

Disconnect from Sendbird server

Copy link

When a user doesn’t need to receive messages from the Sendbird server, it is recommended to disconnect the user from the server. Even after disconnected, the user can still receive push notifications for new messages delivered by APNs (Apple Push Notification Service).

SendbirdUI.disconnect {}

Register for push notifications

Copy link

Push notifications are a type of notification sent to your user's device when a client app is running in the background. Sendbird server will communicate with APNs whenever needed and APNs will send a push notification to the client app on iOS devices. Push notifications for the client app will contain a payload created by Sendbird and be delivered through APNs. In order to use this feature, you need to register the user's device token to Sendbird server through the AppDelegate.

Note : In the SwiftUI project, we set up APNs by adding an AppDelegate.

// unique: The default is `false`. If `true`, register device token after
// removing all existing device tokens of the current user. If `false`, just add the device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  SendbirdUI.registerPush(deviceToken: deviceToken, unique: true) { (success) in
  // Handle success or failure
  }
}

Note : You can use these methods when the SBUGlobals.currentUser is set and connected to Sendbird server.


Handle push notification event

Copy link

Sendbird Chat SwiftUI includes a PushPayloadManager that handles secondary events on behalf of the user when a push notification is received. The PushPayloadManager processes the logic for navigating to the channel with the received message in the channel list after receiving a push notification or emits the push event through its Combine publisher, pushNotificationPublisher.

To deliver a push event to the PushPayloadManager, use the save method in the UNUserNotificationCenterDelegate to pass the userInfo information.

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
      let userInfo = response.notification.request.content.userInfo
      
     // Update information
      SendbirdUI.PushPayloadManager.save(userInfo: userInfo)
  }
}

Users can subscribe to Sendbird's push events through the pushNotificationPublisher provided by the PushPayloadManager. In a SwiftUI view, it can be used as follows:

@State var showChannelList = false

var body: some View {
  NavigationView {
      NavigationLink(isActive: $showChannelList, destination: {
          GroupChannelListView()
      }) {
          EmptyView()
      }
      .navigationTitle("Sample List")
      .onReceive(SendbirdUI.PushPayloadManager.pushNotificationPublisher) { _ in 
          showChannelList = true
      }
  }

  // If iOS 16 is available 
  NavigationStack {
      EmptyView()
      .navigationTitle("Sample List")
      .onReceive(SendbirdUI.PushPayloadManager.pushNotificationPublisher) { _ in 
          showChannelList = true
      }
      .navigationDestination(isPresented: $showChannelList) {
          GroupChannelListView()
      }
  }
}

Note : If a view that subscribes to a publisher using onReceive is not present in the SwiftUI view hierarchy, it will not receive events. To continuously observe events, it is recommended to subscribe to events from the app’s root view.


Unregister for push notifications

Copy link

You should unregister a user's device token from Sendbird server if you don’t want to send push notifications to the user.

// If you want to unregister the current device only, call this method.
SendbirdUI.unregisterPushToken { (success) in

}

// If you want to unregister all devices of the user, call this method.
SendbirdUI.unregisterAllPushToken { (success) in

}

Note : You can use these methods when the SBUGlobals.currentUser is set and connected to Sendbird server.


Update user profile

Copy link

When a currentUser is created with a unique ID, Sendbird Chat SwiftUI automatically generates nickname and profileImage of the user based on the specified userId. You can also modify these properties by yourself when needed.

Note : You can use this method when the SBUGlobals.currentUser is set and connected to Sendbird server.

// Update Using Profile URL. If the parameter value is nil, it will not be updated
SendbirdUI.updateUserInfo(nickname: {NICKNAME}, profileURL: {PROFILE_URL}) { (error) in
    guard error == nil else {
        // Handle error
        print("Failed to update user info: \(error!.localizedDescription)")
        return
    }
    // Continue with additional code if there's no error
}

// Update Using Profile Image Data. If the parameter value is nil, it will not be updated
SendbirdUI.updateUserInfo(nickname: {NICKNAME}, profileImage: {PROFILE_IMAGE_DATA}) { (error) in
    guard error == nil else {
        // Handle error
        print("Failed to update user info: \(error!.localizedDescription)")
        return
    }
    // Continue with additional code if there's no error
}