iOS SDK

This tutorial provides you with a step-by-step guide to configuring your iOS SDK in your mobile application.

You can add HelpCrunch iOS SDK to your project using CocoaPods. It requires iOS >=10 , XCode 10 and >=Swift 4.0. Also we have dependency on Socket.IO >= v13. Don’t worry, if you’re not using it – it will be automatically downloaded by CocoaPods. We support both ObjectiveC and Swift apps.

If you need older version, that is written in objc and can be installed without CocoaPods, check here

We will start on configuring your app in your HelpCrunch profile, then proceed to implementing and configuring HelpCrunch SDK in your iOS project, and finally, we’ll describe how to create a push-enabled iOS application and send notifications to users.

Configuring app on your HelpCrunch profile

Install HelpCrunch SDK by CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 43 thousand libraries and is used in over 3 million apps. CocoaPods can help you scale your projects elegantly. If you haven’t used it before, please start here.

To integrate HelpCrunch into your Xcode project using CocoaPods, specify it in your Podfile (text file named Podfile in your Xcode project directory):

use_frameworks!

target 'ProjectTargetName' do
  pod 'HelpCrunchSDK'
end

Now you can install the dependencies in your project:

$ pod install

Make sure to always open the Xcode workspace instead of the project file when building your project:

$ open App.xcworkspace

Create a new app

To add a new app, login into your HelpCrunch account, then go to the Settings pageSet up & CustomizeiOS APPs and press “Add new”. Fill the iOS App Name field and press “Apply” button:

iOS Apps

Add APNS certificate

If you plan to use push notifications to inform your application users about new messages from HelpCrunch, you will need to add APNS certificate and APNS certificate passpharse to the app. Skip this step if you do not plan to use push notifications. More details about push notification integration can be found in Enabling Push Notifications section

Adding SDK to your project

  1. Install sdk via CocoaPods
  2. Add the following import to the top of the AppDelegate.m:
    ObjC:
    #import <HelpCrunchSDK/HelpCrunch.h>
    Swift: import HelpCrunchSDK
  3. Initialize the Helpcrunch SDK in HelpCrunchSDK/HelpCrunch.h file:
    ObjC:
    [HelpCrunch initForOrganization:@"YOUR_HELPCRUNCH_SUBDOMAIN" withAttributes:@{
      HC_ApplicationIdAttributeName:@"YOUR_APP_ID",
      HC_ApplicationSecretAttributeName:@"YOUR_APP_SECRET"
    } completionHandler:^(BOOL succeeded, NSError *error) {}];
    Swift:
    HelpCrunch.initForOrganization("YOUR_HELPCRUNCH_SUBDOMAIN",
     withAttributes:[
      HC_ApplicationIdAttributeName:"YOUR_APP_ID",
      HC_ApplicationSecretAttributeName:"YOUR_APP_SECRET"
    ]) { (succeeded, error) in  }

    You can copy this code on apps list in your HelpCrunch account

  4. By default HelpCrunch SDK is initialized on the app startup, so that you can always get the latest data about your users. We also recommend to implement the method [HelpCrunch restoreFromBackground];/ HelpCrunch.restoreFromBackground() in application WillEnterForeground to initialize the HelpCrunch SDK when the app is restored from background.
  5. To show the HelpCrunch UI simply call the showFromController helper method on HelpCrunch:
    ObjC:
    [HelpCrunch showFromController:viewController];
    
    Swift:
    HelpCrunch.show(from: viewController)

    viewControllerrequired – the controller to be presented from.

  6. You can check if chat is currently displayed using:
    [HelpCrunch isShowing] / HelpCrunch.isShowing()
  7. After you have called the showFromController method it will look like this:iOS App

Enable Push Notifications (optional)

We believe that push notifications are a great way to add real-time messaging to your application and inform your app users that there is a new message came from HelpCrunch server (i.e. from your admin dashboard). It allows you to stay in touch with your users even when the application is not in the foreground. Although, HelpCrunch Mobile SDK does not necessary require the implementation of push notifications and end users of your application will still be able to receive messages, but in this case, the end users will discover that new messages arrived only after opening HelpCrunch page.

When implementing push notifications in your app, you should remember that push notifications are not available in the iOS Simulator. To start developing this featured you will need an iOS device, as well as an Apple Developer license.

Add Code for a Push Enabled iOS Applications

To register the current device for push add the following code in the app delegate’s -application:didFinishLaunchingWithOptions: method:

ObjC:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...
  [HelpCrunch initForOrganization:@"YOUR_HELPCRUNCH_SUBDOMAIN" withAttributes:@{
    HC_ApplicationIdAttributeName:@"YOUR_APP_ID",
    HC_ApplicationSecretAttributeName:@"YOUR_APP_SECRET"
  }];
  
  [HelpCrunch registerForRemoteNotifications];
  if (![HelpCrunch didReceiveRemoteNotificationWithLaunchOptions:launchOptions]) {
    // this push notification does not belong to HelpCrunch
  }
  ...
  
  return YES;
}
Swift:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ...
    HelpCrunch.initForOrganization("YOUR_HELPCRUNCH_SUBDOMAIN",
 withAttributes:[
       HC_ApplicationIdAttributeName:"YOUR_APP_ID",
       HC_ApplicationSecretAttributeName:"YOUR_APP_SECRET"
    ]) { (succeeded, error) in  }
    HelpCrunch.registerForRemoteNotifications()
    
    if (!HelpCrunch.didReceiveRemoteNotification(launchOptions: launchOptions)) {
            // this push notification does not belong to HelpCrunch
    }

If the registration is successful, the callback method
-application:didRegisterForRemoteNotificationsWithDeviceToken:
in the application delegate will be executed. We will need to implement this method and use it to inform HelpCrunch about this new device.

ObjC:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [HelpCrunch setDeviceToken:deviceToken];
}
Swift:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    HelpCrunch.setDeviceToken(deviceToken)
}

When a push notification is received while the application is in the background, it is displayed in the iOS Notification Center. However, if the notification is received while the app is active, it is up to you how to handle it. To do so, we can implement the [application:didReceiveRemoteNotification] method in the app delegate. In our case, we will simply ask HelpCrunch to handle it for us. HelpCrunch will create a modal alert and display the push notification’s content.

ObjC:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  if (![HelpCrunch didReceiveRemoteNotification:userInfo]) {
    // this push notification does not belong to HelpCrunch
  }
}
Swift:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if (!HelpCrunch.didReceiveRemoteNotification(userInfo)) {
      // this push notification does not belong to HelpCrunch
    }
}

You can disable a default alert and implement your own alert. For disabling a default alert:
ObjC:
[HelpCrunch useDefaultAlertForRemoteNotification:NO]; // Defaults to YES

Swift:
HelpCrunch.useDefaultAlert(forRemoteNotification: false) // Defaults to YES

App Users

By default HelpCrunch SDK requires a user to enter his name before sending messages. You can disable this with following code:
ObjC:
[HelpCrunch customerNameRequired:NO]; // Defaults to YES

ObjC:
HelpCrunch.customerNameRequired(false) // Defaults to YES

Saving app user data to HelpCrunch is done by calling [HelpCrunch updateUser:completionHandler:] / HelpCrunch.updateUser([:]) { succeeded, error in }.
Be sure to put a unique User ID string in withUserID method for all your users. Constructing empty users with no data will not work (you can have no use of an empty user you cannot identify after all).

ObjC:
NSDictionary *user = @{
  HC_UserNameAttributeName: @"Username",
  HC_UserEmailAttributeName: @"Email",
  HC_UserPhoneAttributeName: @"Phone",
  HC_UserIdAttributeName: @"UserId",
  HC_CustomDataAttributeName: @{
    @"CustomKey1": @"CustomObject1",
    @"CustomKey2": @"CustomObject2",
    @"CustomKey3": @"CustomObject3"
  }
};
[HelpCrunch updateUser:user completionHandler:^(BOOL succeeded, NSError *error) {}];
Swift:
let attributes = [HC_UserNameAttributeName: "Username",
                  HC_UserEmailAttributeName: "Email",
                  HC_UserPhoneAttributeName: "Phone",
                  HC_UserIdAttributeName: "UserId",
                  HC_CustomDataAttributeName: 
                     ["CustomKey1": "CustomObject1",
                      "CustomKey2": "CustomObject2",
                      "CustomKey3": "CustomObject3"]
]
HelpCrunch.updateUser(attributes) { succeeded, error in }

You can also pass a user data when initializing HelpCrunch in your application:

ObjC:
[HelpCrunch initForOrganization:@"YOUR_HELPCRUNCH_SUBDOMAIN"
withAttributes:@{
  HC_ApplicationIdAttributeName:@"YOUR_APP_ID",
  HC_ApplicationSecretAttributeName:@"YOUR_APP_SECRET",
  HC_UserAttributeName: user
}];
Swift:
HelpCrunch.initForOrganization("YOUR_HELPCRUNCH_SUBDOMAIN"
    withAttributes:
        [HC_ApplicationIdAttributeName:"YOUR_APP_ID",
         HC_ApplicationSecretAttributeName:"YOUR_APP_SECRET",
         HC_UserAttributeName:userName]) { succeeded, error in }

After you have added user’s data it will appear in your HelpCrunch admin account in chat with that user:

Sent User data in chat
In addition to user’s name / email / and ID HelpCrunch lets you send additional attributes of your customers in custom data. With the HC_CustomDataAttributeName you can send any information about users you wish to track. Custom data is key/value pairs and can contain numbers, strings or boolean data. This feature will only work if you have your user have a HC_UserIdAttributeName:


NSDictionary *user = @{
  HC_UserIdAttributeName: @"UserId",
  HC_CustomDataAttributeName: @{
    @"CustomKey1": @"CustomObject1",
    @"CustomKey2": @"CustomObject2",
    @"CustomKey3": @"CustomObject3"
  }
};

[HelpCrunch updateUser:user completionHandler:^(BOOL succeeded, NSError *error) {}];

Custom data parameters will appear in chat with user at your HelpCrunch admin account just as same as main user attributes (name, email, user id):

Custom data in chat

Also you will be able to search through your users by custom data you at the “Contacts” page. There 3 types of custom data you can search by: integers, strings and boolean:

Custom data search

Messages

In order to display the number of new messages in your application, fetch unread messages from the server. Use once after initializing HelpCrunch SDK:

ObjC:
[HelpCrunch checkUnreadMessages:^(NSUInteger numberOfUnreadMessages) {
  // show a badge somewhere in your application
}];
Swift:
HelpCrunch.checkUnreadMessages { (numberOfUnreadMessages) in
  // show a badge somewhere in your application
}

Initiate every time you want to display the number on unread messages on UI using the following method:
ObjC:
NSUInteger numberOfUnreadMessages = [HelpCrunch numberOfUnreadMessages];

Swift:
let numberOfUnreadMessages = HelpCrunch.numberOfUnreadMessages()

Localization

To be able to localize your chat in your application or change it’s texts you need to:

  1. Create a “localizable.string” and select desirable localization:
  2. Then add string resources to Localizable.string file with needed texts. In HelpCrunch SDK you can use these names:

    "helpcrunch.chat.title" = "Help & Feedback";
    "helpcrunch.chat.welcome-message" = "Your suggestions, ideas or complaints greatly help us. We'll get back to you pretty soon!";
    "helpcrunch.chat.button.send" = "Send";
    "helpcrunch.chat.deleted.alert.error" = "The chat was removed by agent. You'll be logged out.";
    "helpcrunch.alert.title" = "Help & Feedback";
    "helpcrunch.alert.button.cancel" = "Cancel";
    "helpcrunch.alert.button.reply" = "Reply";
    "helpcrunch.alert.button.ok" = "OK";
    "helpcrunch.connection.alert.error" = "Connection Error";
    "helpcrunch.connection.no-internet-connection.alert.title" = "No Internet Connection";
    "helpcrunch.connection.no-internet-connection.alert.text" = "Message will be sent once connection restored";
    "helpcrunch.connection.unknown-error" = "Unknown server error";
    "helpcrunch.profile.title" = "Profile";
    "helpcrunch.profile.enter-your-name" = "Enter your name";

Login/logout/user change

If you use user authentication mode and have a logout and you want to be sure, that new logged user will have other chat than the previous one, you can use login and logout method. Check this examples to see how you can do it in your application:
Login example

ObjC:
- (IBAction)loginPressed:(id)sender {
  NSMutableDictionary *userData = [[NSMutableDictionary alloc] init];

  if (![self fieldIsEmpty:self.nameTextField]) {
    [userData setValue:_nameTextField.text forKey:HC_UserNameAttributeName];
  }
  
  if (![self fieldIsEmpty:self.emailTextField]) {
    [userData setValue:_emailTextField.text forKey:HC_UserEmailAttributeName];
  }
  
  [userData setValue:self.userId forKey:HC_UserIdAttributeName];
  [HelpCrunch updateUser:userData completionHandler:^(BOOL succeeded, NSError *error) {
     // We're ready to log user in
  }];
}
Swift:
@IBAction func buttonLoginPressed(_ sender: Any) {
  var userData:[String: Any] = [HC_UserIdAttributeName:userId]

  if nameTextField.text.count > 0 {
    userData[HC_UserNameAttributeName] = nameTextField.text
  }
  
  if emailTextField.text.count > 0 {
    userData[HC_UserEmailAttributeName] = emailTextField.text
  }
  
  HelpCrunch.updateUser(userData) { (succeeded, error) in
     // We're ready to log user in
  }
}

Logout example:

ObjC:
- (IBAction)logout:(id)sender {
  [HelpCrunch logout:^(BOOL succeeded, NSError *error) {
    if (succeeded) {
      // User successfully logged out
    }
  }];
}
Swift:
@IBAction func buttonLogoutPressed(_ sender: Any) {
    HelpCrunch.logout { (succeeded, error) in
        // User successfully logged out
    }
}