> For the complete documentation index, see [llms.txt](https://platform-business.gitbook.io/klat/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://platform-business.gitbook.io/klat/ios/push-notification.md). Agents can also search and read this documentation through its [MCP server](https://platform-business.gitbook.io/klat/~gitbook/mcp).

# Push Notification

### Enable / Disable Push Notification

사용자가 Push Notification을 받을 지 여부를 설정할 수 있습니다.

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
// 사용자 Push Notification 활성화
[[TalkPlus sharedInstance] enablePushNotification:^(TPUser *tpUser) {
    // SUCCESS
} failure:^(int errorCode, NSError *error) {
    // FAILURE    
}];

// 사용자 Push Notification 비활성화
[[TalkPlus sharedInstance] disablePushNotification:^(TPUser *tpUser) {
    // SUCCESS
} failure:^(int errorCode, NSError *error) {
    // FAILURE    
}];
```

{% endtab %}

{% tab title="Swift" %}

```swift
// 사용자 Push Notification 활성화
TalkPlus.sharedInstance().enablePushNotification { tpUser in
    // SUCCESS
} failure: { (errorCode, error) in }
    // FAILURE    
}

// 사용자 Push Notification 비활성화
TalkPlus.sharedInstance().disablePushNotification { tpUser in
    // SUCCESS
} failure: { (errorCode, error) in }
    // FAILURE    
}
```

{% endtab %}
{% endtabs %}

특정 채널의 Push Notification을 받을 지 여부를 설정할 수 있습니다.

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
// 채널 Push Notification 활성화
[[TalkPlus sharedInstance] enableChannelPushNotification:channel 
    success:^(TPChannel *tpChannel) {
    // SUCCESS
} failure:^(int errorCode, NSError *error) {
    // FAILURE    
}];

// 채널 Push Notification 비활성화
[[TalkPlus sharedInstance] disableChannelPushNotification:channel 
    success:^(TPChannel *tpChannel) {
    // SUCCESS    
} failure:^(int errorCode, NSError *error) {
    // FAILURE
}];
```

{% endtab %}

{% tab title="Swift" %}

```swift
// 채널 Push Notification 활성화
TalkPlus.sharedInstance().enableChannelPushNotification(channel) { channel in
    // SUCCESS
} failure: { (errorCode, error) in 
    // FAILURE  
}

// 채널 Push Notification 비활성화
TalkPlus.sharedInstance().disableChannelPushNotification(channel) { channel in
    // SUCCESS
} failure: { (errorCode, error) in
    // FAILURE  
}
```

{% endtab %}
{% endtabs %}

### Push Notification

Klat의 Push Notification은 FCM을 통하여 이루어지게 됩니다. 기본적인 FCM을 연동하신 후, User를 로그인한 후 `registerFCMToken` 함수를 호출하여 FCM 토큰을 User 세션에 연동하여야 합니다.

로그인이 완료된 후 아래와 같이 `FIRMessaging`을 통하여 token을 얻어 register 하시는 것을 권장 드립니다.

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
#import <UserNotifications/UserNotifications.h>
@import Firebase;

// 파이어베이스 초기화
[FIRApp configure];
    
// 푸시 권한 요청
UNUserNotificationCenter *center = 
    [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)
    completionHandler:^(BOOL granted, NSError *error) {
    NSLog(@"granted: %@", granted ? @"YES":@"NO");
}];

// Firebase Messaging을 통하여 현재 token을 획득
[[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Error getting FCM registration token: %@", error);
    } else {
        NSLog(@"FCM registration token: %@", token);
        [self registerFCMToken:token];
    }
}];

-(void)registerFCMToken:(NSString *)fcmToken {
    [[TalkPlus sharedInstance] registerFCMToken:fcmToken success:^{
        NSLog(@"fcmToken register success");
    } failure:^(int errorCode, NSError *error) {
        NSLog(@"fcmToken register failure");
    }];
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
import Firebase
import FirebaseMessaging
import TalkPlus

// 파이어베이스 초기화
FirebaseApp.configure()

// 푸시 권한 요청
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
    print(granted)
}
application.registerForRemoteNotifications()

Messaging.messaging().token { [weak self] token, error in
    guard let token = token else { return }
    if(error != nil) {
        print("Error getting FCM registration token: \(String(describing: error))")
        return
    }
    print("FCM registration token: \(token)");
    self?.registerFCMToken(fcmToken: token)
}

func registerFCMToken(fcmToken:String){
    TalkPlus.sharedInstance().registerFCMToken(fcmToken) {
        print("fcmToken register success")
    } failure: { errorCode, error in
        print("fcmToken register failure")
    }
}
```

{% endtab %}
{% endtabs %}

그 후 Push Notification이 도착할 경우 아래와 같이 Klat에서 `handleFCMMessage` 함수를 통하여 payload를 처리하여 기존 등록된 delegate로 이벤트를 전달 드립니다.

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
    willPresentNotification:(UNNotification *)notification
    withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    // foreground 상태에서 push가 실행될 때 수신
    NSDictionary *userInfo = notification.request.content.userInfo;
    if ([userInfo objectForKey:@"talkplus"] != nil) {
        NSLog(@"talkplus payload");
        [[TalkPlus sharedInstance] handleFCMMessage:[userInfo objectForKey:@"talkplus"]];
    }
    if (@available(iOS 14, *)) {
        completionHandler(UNNotificationPresentationOptionBadge|
                          UNNotificationPresentationOptionSound|
                          UNNotificationPresentationOptionBanner);
    } else {
        completionHandler(UNNotificationPresentationOptionBadge|
                          UNNotificationPresentationOptionSound);
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
    didReceiveNotificationResponse:(UNNotificationResponse *)response
    withCompletionHandler:(void (^)(void))completionHandler
{
    // background 상태에서  push를 클릭했을 때 호출
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if ([userInfo objectForKey:@"talkplus"] != nil) {
        // 웹 소켓 연결을 통해서 처리
        NSLog(@"talkplus payload found, but do nothing");
    }
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
func userNotificationCenter(_ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    // foreground 상태에서 push가 실행될 때 수신
    let userInfo = notification.request.content.userInfo
    if let payload = userInfo["talkplus"] as? String {
        print("talkplus payload")
        TalkPlus.sharedInstance().handleFCMMessage(payload)
    }
    if #available(iOS 14.0, *) {
        completionHandler([.sound, .badge, .banner])
    } else {
        // Fallback on earlier versions
        completionHandler([.sound, .badge])
    }
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void) 
{
    // background 상태에서  push를 클릭했을 때 호출
    let userInfo = response.notification.request.content.userInfo
    if let _ = userInfo["talkplus"] as? String {
        // 웹 소켓 연결을 통해서 처리
        print("talkplus payload found, but do nothing")
    }
}
```

{% endtab %}
{% endtabs %}
