Xcode Chat SDK Setup


SDK contents


Once you've downloaded and unzipped the PUSHTech™ Chat SDK, you'll find three directories:

  • Documentation folder: contains the SDK documentation as plain HTML formatted as Apple do and as XCode docset.

  • PushTechSDK folder: contains the PushTechChatSDK.framework and PushTechSDKResources.bundle files.

  • PushTechSDKDemo folder: contains the demo project for the PushTechChatSDK.

Xcode Project Setup


Note: If you have already installed the PUSHTech™ SDK without chat, you will be able to use all the features of the PUSHTech™ SDK plus the CHAT features, to do so, delete the PushTechSDK folder from your project and follow the steps in this tutorial, you can keep your existing code, just add or change the code described below to your existing project. It's also important that you setup your project correctly, so pay attention to the XCode Setup Section.

  • Drag and drop the PushTechChatSDK into your project and make sure 'Copy items if needed', 'Create folder references' and your project's target are selected on the import dialog.

  • Ios chat sdk setup 1
  • If you don't use cocoapods yet, it's time to visit the CocoaPods site and install the awesome CocoaPods dependency manager.

  • Once you have CocoaPods installed, create a text file named 'Podfile' in your project's folder like so:

  • Ios chat sdk setup 2
  • The contents of your Podfile should look something like this:

  • platform :ios, '6.0'
    inhibit_all_warnings!
    
    target 'YourProjectName' do
    
      pod 'MagicalRecord', '2.2'
      pod 'MBProgressHUD', '0.8'
      pod 'RHAddressBook', '1.1.0'
      pod 'HPGrowingTextView', '1.1'
      pod 'TTTAttributedLabel', '1.8.1'
      pod 'SocketRocket', '0.2.0'
      pod 'MKNetworkKit', '0.87'
      pod 'MWPhotoBrowser', '1.4'
      pod 'PBWebViewController', '0.1'
      pod 'CMNavBarNotificationView', '1.0'
    
      #Add your project's dependencies here.
    
    end
  • Fire up your favorite terminal, navigate to your project's folder, and run pod install.

  • If cocoapods succeeded with the project's setup, you're ready to start using the PushTechChatSDK.

Objective C Implementation


Import the required header files

At the top of you application delegate, import the umbrella header file:

#import <PushTechChatSDK/PushTechChatSDK.h>

Setup your AppDelegate

First we declare some private properties we're going to use with a class extension:

#pragma mark - Private

@interface PushTechChatSDKDemoDelegate () 

@property (nonatomic, strong) UITabBarController* chatTabBarController;
@property (nonatomic, strong) MBProgressHUD* hud;
@property (nonatomic, strong) MWPhoto* currentPhoto;

@end

Notice that our delegate class implements PSHChatViewDelegate protocol methods. Since we're going to use the whole UI PushTechChatSDK provides, the application delegate is assumed as PSHChatViewController delegate. You can check this out in the documentation.

Paste this code in your -application:didFinishLaunchingWithOptions: method in the AppDelegate.

//1
[PSHChatEngine initializeWithAppId:@"YOUR-APP-ID"
  appSecret:@"YOUR-APP-SECRET"
  logLevel:PSHLogLevelDebug];

//2
[[PSHBusProvider sharedInstance] addListener:self];

//3
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    //iOS8
    UIUserNotificationType myTypes = (UIUserNotificationTypeBadge |
                                      UIUserNotificationTypeAlert |
                                      UIUserNotificationTypeSound);
    UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:myTypes
                                          categories:nil];
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
} else {
    //iOS6, iOS7
    UIRemoteNotificationType myTypes =  UIRemoteNotificationTypeBadge |
                                        UIRemoteNotificationTypeAlert |
                                        UIRemoteNotificationTypeSound;
    [application registerForRemoteNotificationTypes:myTypes];
}

//4
[self setupAppearance];

//5
[self setupControllers];
  • First, you must initialize the SDK with the AppId and secret that was given to you when registering your app.

  • Second, you must subscribe to bus events to receive notifications when relevant SDK events happen like, successfully registering a device.

  • Third, register your application to receive Push Notifications.

  • Fourth, modify the app's UI using the Appearance proxy.

  • - (void)setupAppearance
    {
      UIColor* mainBlack = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
      if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
          [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
          [[UINavigationBar appearance] setBarTintColor:mainBlack];
          [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
          [[UINavigationBar appearance] setTitleTextAttributes:@{UITextAttributeTextColor: [UIColor whiteColor]}];
    
          [[UIToolbar appearance] setBarTintColor:[UIColor lightGrayColor]];
          [[UIToolbar appearance] setTintColor:[UIColor whiteColor]];
    
          [[UITabBar appearance] setBarTintColor:[UIColor lightGrayColor]];
          [[UITabBar appearance] setTintColor:[UIColor whiteColor]];
      } else {
          [[UINavigationBar appearance] setTintColor:mainBlack];
          [[UINavigationBar appearance] setTitleTextAttributes:@{UITextAttributeTextColor: [UIColor whiteColor]}];
    
          [[UIToolbar appearance] setTintColor:[UIColor lightGrayColor]];
    
          [[UITabBar appearance] setTintColor:[UIColor lightGrayColor]];
          [[UITabBar appearance] setSelectedImageTintColor:[UIColor whiteColor]];
      }
    }
    
  • Fifth, setup the root view controller ad present the corresponding dialogs.

  • - (void)setupControllers
    {
      PSHChatEngine* engine = [PSHChatEngine sharedInstance];
      _chatTabBarController = [engine instantiateMainTabBarViewController];
      _chatTabBarController.selectedIndex = 1; // appear showing the chat list
      self.window.rootViewController = _chatTabBarController;
      [self.window makeKeyAndVisible];
    
      if (engine.isAppRegistered) {
          if (engine.isChatEnabled) {
              if (!engine.isInDomain) {
                  [self presentChatRegistrationUI];
              }
          }
      }
      else {
          // block UI until we know app is registered
    
          _hud = [MBProgressHUD showHUDAddedTo:_chatTabBarController.view animated:YES];
          _hud.dimBackground = YES;
      }
    }
  • Alert Only for iOS6 Sixth, if you are supporting iOS6 you will need to find out if the application was launched by a push notification and redirect the info to the method that will handle it. To do so, paste this code at the end of the implementation of application:didFinishLaunchingWithOptions::

  • //6 only in iOS6
    NSDictionary* pushNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (pushNotification)
    {
        [self application:application didReceiveRemoteNotification:pushNotification fetchCompletionHandler:nil];
    }

    After instantiating the main tabbed bar view controller and make it your app root view controller, we need to check some state properties and implement some flow logic. We get the singleton PSHEngine and then check if our app is registered, which just means that the SDK has updated its internal model with the information provided by Push Technologies platform given an app id and secret. Don't worry, this will only happen the first time your user launches the app. Then, if the app is still not registered, we block the UI using MBProgressHUD library until we receive a bus event telling us that the app has been registered successfully (we'll see this further in this guide).

    Otherwise, we check if the chat feature is enabled and finally if the user is in (chat) domain, in other words if he/she has registered in the chat. If the last condition is not accomplished, we just present the chat registration UI our SDK provides.

    Once the application has successfully registered for Push Notifications on the Apple Servers, you have to register the token that apple gave you in our platform's servers so we know where to send the notifications. To do that you'll need to paste this code in your AppDelegate:

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
        [[PSHEngine sharedInstance] registerPushToken:deviceToken];
    }

    You must also implement bus event listener methods. Here we have all the listeners to get incoming chat message notifications. As you can see in the documentation, our event bus approach is an abstraction layer over NSNotificationCenter, so the method has a NSNotification argument.

    #pragma mark - Event bus listener
    
    -(void)onSuccessfulAppRegistrationBusEvent:(NSNotification*)notification
    {
        NSLog(@"App is registered.");
    
        if (_hud) {
            [MBProgressHUD hideHUDForView:_chatTabBarController.view animated:YES];
            _hud = nil;
        }
    
        if ([PSHEngine sharedInstance].isChatEnabled) {
            NSLog(@"Chat is enabled, will present registration UI.");
    
            [self presentChatRegistrationUI];
        }
        else {
            NSLog(@"Chat is disabled.");
        }
    }
    
    -(void)onSuccessfulDeviceIdBusEvent:(NSNotification*)notification
    {
      NSString *deviceId = [PSHEngine sharedInstance].deviceId;
    
      // Need a DeviceID te be able to send notifications using the PUSH Techoloigies server API.
      // The app will normally send the DeviceID to a backend server that later will use it to send requests to the PUSH Tecnologies server.
        NSLog(@"Received DeviceID = %@.", deviceId);
    }
    
    -(void)onIncomingMessageChatBusEvent:(NSNotification*)notification
    {
      // Received a chat message notification
      PSHSuccessfulDeviceIdBusEvent* event = (PSHSuccessfulDeviceIdBusEvent*) notification.object;
      NSString *chatNotif = event.text;
      NSLog("Chat Notification = %@", chatNotif);
    }
    
    #pragma mark - Chat registration
    
    -(void)presentChatRegistrationUI
    {
        UINavigationController* registrationController = [[PSHEngine sharedInstance] instantiateRegistrationNavigationController];
        [self.window.rootViewController presentViewController:registrationController animated:YES completion:nil];
    }

    Almost done! As we previously saw our application delegate is going to be also any PSHChatViewController delegate. The PSHChatViewDelegate protocol offers a lot flexibility as you can see:

    #pragma mark - PSHChatViewDelegate
    
    #define MAKE_ACTIVITY(text,callback) [[PSHChatViewControllerShareActivity alloc] initWithText:NSLocalizedString(text, nil) andCallback:callback];
    
    -(void)PSHChatViewDidLoad:(PSHChatViewController*)chatView
    {
        PSHChatViewControllerShareActivity* a1 = MAKE_ACTIVITY(@"CONVERSATION_TAKE_A_PICTURE", ^(PSHChatViewController* chatView) {
            [chatView performTakeAndSendPicture];
        });
        PSHChatViewControllerShareActivity* a2 = MAKE_ACTIVITY(@"CONVERSATION_TAKE_A_VIDEO", ^(PSHChatViewController* chatView) {
            [chatView performTakeAndSendVideo];
        });
        PSHChatViewControllerShareActivity* a3 = MAKE_ACTIVITY(@"CONVERSATION_CAMERA_ROLL", ^(PSHChatViewController* chatView) {
            [chatView performPickMediaFromCameraRollAndSend];
        });
        PSHChatViewControllerShareActivity* a4 = MAKE_ACTIVITY(@"CONVERSATION_SEND_LOCATION", ^(PSHChatViewController* chatView) {
            [chatView performSendLocation];
        });
        PSHChatViewControllerShareActivity* a5 = MAKE_ACTIVITY(@"CONVERSATION_SEND_CONTACT", ^(PSHChatViewController* chatView) {
            [chatView performSendContact];
        });
    
        chatView.shareActivities = @[a1, a2, a3, a4, a5];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView didTapOnImageWithURL:(NSURL*)imageURL
    {
      // e.g. we could use MWPhoto library to show the image
      // (https://github.com/mwaterfall/MWPhotoBrowser)
    
        self.currentPhoto = [MWPhoto photoWithURL:imageURL];
    
        MWPhotoBrowser* browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        browser.displayActionButton = NO;
    
        [chatView.navigationController pushViewController:browser animated:YES];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView didSelectLinkWithURL:(NSURL*)url
    {
        [[UIApplication sharedApplication] openURL:url];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView didSelectLinkWithPhoneNumber:(NSURL*)url
    {
        [[UIApplication sharedApplication] openURL:url];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView shouldPushContactViewController:(ABPersonViewController*)newPersonViewController
    {
        [chatView.navigationController pushViewController:newPersonViewController animated:YES];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView shouldPushLocationViewController:(UIViewController*)viewController
    {
        [chatView.navigationController pushViewController:viewController animated:YES];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView shouldPresentPeoplePickerNavigationController:(ABPeoplePickerNavigationController*)newPeoplerPickerNavigationController
    {
        [self.window.rootViewController presentViewController:newPeoplerPickerNavigationController animated:YES completion:nil];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView shouldPresentUIImagePickerController:(UIImagePickerController*)newImagePickerController
    {
        [self.window.rootViewController presentViewController:newImagePickerController animated:YES completion:nil];
    }
    
    -(void)PSHChatView:(PSHChatViewController*)chatView presentMoviePlayerViewControllerAnimated:(MPMoviePlayerViewController*)newPlayerViewController
    {
        [self.window.rootViewController presentMoviePlayerViewControllerAnimated:newPlayerViewController];
    }
    
    @end

    Each delegate method gives us the opportunity to present our own view controllers or perform custom actions when relevant events happen.

    Congratulations! You can start using the SDK on your own with the documentation provided with the SDK. If you had problems setting up your project or anything strange happened, you can take a look to the Demo project and check if your setup is alright.