Перейти к основному содержимому
Версия: 4.31.0

Инструкции по миграции

Переход на версию 4.0.0

В версии 4.0.0 переработана интграция и работа с пуш-библиотекой.

  • Пуш-библиотека MFMSPushLite убрана внутрь Threads, все взаимодействие теперь происходит только через него.
  • Для показа чата теперь предоставляется UIViewController

Подключение через CocoaPods

Если вы подключаете Threads через CocoaPods - уберите ручное подключение MFMSPushLite. Теперь зависимость подтягивается автоматически

Конфигурация Threads

Замените все вызовы статических методов класса Threads на обращение к синглтону [Threads threads]

В Application didFinishLaunchingWithOptionsдо регистрации пушей, добавьте метод конфигурации Threads(он содержит в себе конфиграцию MFMSPushLite):

Threads *threads = [Threads threads];

[threads configureWithDelegate:self
productionMFMSServer:YES
historyURL:[NSURL URLWithString:@"HISTORY_URL"]
fileUploadingURL:[NSURL URLWithString:@"FILE_UPLOADING_URL"]];
  • Уберите из Info.plist словарь PS_API_CONFIG с параметрами PS_FILE_UPLOAD_URLPS_HISTORY_URLPS_CLIENTID_IS_ENCRYPTED - эти параметры больше не задаются в plist, толко в коде.

MFMSPushLiteDelegate -> ThreadsDelegate

Реализацию делегата MFMSPushLiteDelegate замените на реализацию делегата ThreadsDelegate и параметр:

  • Перенесите переключение боевой\тестовой пуш-платформы из метода (BOOL)isProductionWithPushApi:(MFMSPushLite * _Nonnull)pushApi - в параметр productionMFMSServer в Конфигурация Threads
  • Перенесите реализацию методов делагата MFMSPushLiteDelegate
    - (id<PushServerApiConfigDataSource>)configWithPushApi:(MFMSPushLite *)pushApi;

    - (void)onPushMessagesReceivedWithPushApi:(MFMSPushLite *)PushApi messages:(NSArray<PushNotificationMessage *> *)messages;

    - (void)onErrorWithPushApi:(MFMSPushLite *)PushApi error:(NSString *)error;
    В соответствующие методы ThreadsDelegate:
    - (id<PushServerApiConfigDataSource>)threads:(Threads *)threads configurePushServerApiFor:(MFMSPushLite *)mfmsPushLite;
    - (void)threads:(Threads *)threads didReceiveFullMessages:(NSArray<PushNotificationMessage *> *)messages;
    - (void)threads:(Threads *)threads didReceiveError:(NSError *)error;

Настройка приема пуш-уведомлений

Замените код регистрации пушей

if (@available(iOS 10, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!error){
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}
}];
} else {
[[UIApplication sharedApplication] registerForRemoteNotifications];
}

На следующий:

[Threads threads] registerApplicationForRemoteNotificationsStandartOptionsWithAuthorizationStatusDenied:^{
NSLog(@"Remote notifications denied");
} completionHandler:^(NSData * _Nullable deviceToken) {
NSLog(@"Application registered for remote notifications %@", deviceToken);
}];

Замените реализацию методов обработки регистрации и получения пушей на следующие вызовы Threads:

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[Threads threads] applicationDidRegisterUserNotificationSettings:notificationSettings];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[Threads threads] applicationDidRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[Threads threads] applicationDidReceiveRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[[Threads threads] applicationDidReceiveRemoteNotification:userInfo fetchCompletionHandler:^(THRMessageRecieveState state) {
completionHandler(UIBackgroundFetchResultNewData);
}];
}

#pragma mark - UNUserNotificationCenterDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler API_AVAILABLE(ios(10.0)){
[[Threads threads] applicationDidReceiveRemoteNotification:notification.request.content.userInfo fetchCompletionHandler:^(THRMessageRecieveState state) {
completionHandler(UNNotificationPresentationOptionNone);
}];
}

Уберите вызов [Threads didReceiveFullPush:...], теперь пуши передаются напрямую внутри библиотеки.Если вы используете собственные пуши - их можно получить в метода делегата ThreadsDelegate:

- (void)threads:(Threads *)threads didReceiveFullMessages:(NSArray<PushNotificationMessage *> *)messages;

Регистрация пользователя

Уберите вызов [Threads registerClientWithCompletion:^(BOOL state)] - этого метода больше нет

Замените настройку параметров клиента:

[Threads setClientId:(NSString*) clientId]
[Threads setClientName:(NSString*) clientName]
[Threads setData:(NSString*) data]
[Threads setAppMarker: appMarker]
[Threads setClientIdSignature: (NSString*) clientIdSignature]

На метод установки клиента:

[[Threads threads] setClientWithId:(NSString *) clientId
name:(NSString * _Nullable) clientName
data:(NSDictionary * _Nullable) clientDataDict
appMarker:(NSString * _Nullable) clientAppMarker
signature:(NSString *) clientSignature];

Обратите внимание что data теперь передается в виде словаря а не строки.

Открытие чата

Замените вызовы методов

[Threads show];
[Threads showInView:(UIView *)view parentController:(UIViewController *)parentController;

На получение полноценного UIViewController, который можете презентовать любым нативным способом, например

THRAttributes *attributes = [[THRAttributes alloc] init];
UIViewController *chatViewController = [[Threads threads] chatViewControllerWithAttributes:attributes];
[self.navigationController pushViewController:chatViewController animated:YES];

Другие примеры: Открытие чата

Настройки внешнего вида

Перенесите параметры текстов приветственного экрана чата

[Threads setHelloTitle:@"Заголовок"]
[Threads setHelloDescription:@"Описание"]

В параметры THRAttributes:

  • helloTitle
  • helloDescription

Удалите следующие параметры и методы - в связи с переходом на интеграцию viewController они стали неакутальны и были убраны:

  • THRAttributes
    • navigationBarBackgroundColor
    • navigationBarTintColor
    • navigationBarItemFont
    • shouldAnimateShowNavigation
    • shouldAnimatePopNavigation
  • Threads:
    • showToolbarAnimated
    • hideToolbarAnimated
    • showKeyboard
    • hideKeyboard

Дополнительные возможности

Счетчик непрочитанных -> ThreadsDelegate

Перенесите обработку получения числа непрочитанных из блока

[[Threads threads] setUnreadedMessagesCountChanged:^(NSInteger messagesCount)

В реализацию метода ThreadsDelegate:

- (void)threads:(Threads *)threads unreadMessagesCount:(NSUInteger)unreadMessagesCount;