Copied To Clipboard

Swift Code


Integration

Import the NotifyVisitors SDK in your project

  1. Download the SDK from the link given below.
  2. Download SDK

  3. Extract the file and simply include the folder into your project

Configure Info.plist

You can configure the plist via source code or editor

Source Code

Right Click on Info.plist and click on Open as >> Source code Add the following code in it.

  • iOS

        
    <key>NSAppTransportSecurity</key>
             <dict>
    <key>NSAllowsArbitraryLoads</key>
          <true/>
           <key>NSExceptionDomains</key>
  <dict/>
    </dict>
    <key>UIBackgroundModes</key>
            <array>
                 <string>fetch</string>
                 <string>location</string>
                 <string>remote-notification</string>
                </array>
      <key>CFBundleURLTypes</key>
                 <array>
            <dict>
           <key>CFBundleURLName</key>
            <string>"Your Project Identifier Name"</string>
           <key>CFBundleURLSchemes</key>
          <array>
               <string>"yourURLscheme"</string>
         </array>
</dict>
     </array>
     <key>NSLocationAlwaysUsageDescription</key>
     <string>location  is required for geofence</string>
     <key>nvBrandID</key>
                  <integer>52X</integer>
                  <key>nvSecretKey</key>
                  <string>768B370B0002A3DEE5E8CD991DA80A12</string>
                  <key>nvPushCategory</key>
                  <string>nvpush</string>
                  <key>nvViewAutoRedirection</key>
                   <true/><!--OR--><!-- <false/>-->

        

Editor

Add the following keys with their required values

  • Add nvBrandID as Number. This is the Brand Id of your NotifyVisitors account i.e. {BRAND_ID}
  • Add nvSecretKey as String. This is the Brand Id of your NotifyVisitors account i.e. {SECRET_KEY}
  • Add NSAppTransportSecurity as a Dictionary. Then add a Subkey NSAllowsArbitraryLoads as Boolean and set its value to YES.
  • Add URL types as an Array. Under Item 0, add two new items : URL Identifier (string) and URL schemes (Array). Add your company identifier for the URL Identifier and “appScheme” for Item 0 of URL schemes.
  • Add nvPushCategory as String and set it’s value nvpush.
  • Add NSLocationAlwaysUsageDescription as a String. Configure the message you want to show in alert box for asking user permission for geofencing.
  • Add nvViewAutoRedirection as Boolean .Set it YES to enable auto redirection of your app’s ViewControllers from sdk or set it NO to handle redirections by yourself.
  • Go to Project Navigator >> App target >> Capabilities
  • Switch on the Background Modes. Select 3 check boxes i.e. Location updates, Background fetch, Remote notifications.

    Switch on the Push Notifications.

Import header file

Add a new header file and name it with following format. YOUR_PROJECT_NAME- Bridging-Header.h Example if your project name is test. Then the header file name will be test- Bridging-Header.h. Now add the following import statement in YOUR_PROJECT_NAME- Bridging-Header.h for accessing Native SDK Classes.

  • iOS

        #import "notifyvisitors.h"    
        

Make sure that the path of bridge-header.h file is included in build settings under “Swift compiler-code generation” as:


Objective C bridging header:YOUR_PROJECT_NAME/YOUR_PROJECT_NAME-Bridging-Header.h

Initialise the SDK

To initialize the sdk, call the following function in didFinishLaunchingWithOptions method of your project.

  • iOS

       func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        var nvMode:String? = nil
            #if DEBUG
            nvMode = "debug"
            #else
                nvMode = "live"
            #endif
            notifyvisitors.initialize(nvMode)
        }
        

nvMode

Set its value to “debug” or “live” based on preprocessor if condition so that sdk knows the app is running in debugging mode or downloaded from AppStore (i.e. live mode)

Deep Linking

Call the following method in your AppDelegate openURL method that will check the deep linking and open your app from URL Scheme.

  • iOS

        func application(application: UIApplication, openURL url:
            NSURL, sourceApplication: String?, annotation: AnyObject) ->
          Bool {notifyvisitors.openUrl(with: app, url: url)
          return true           
         }   
        

InApp Notifications

InApp Notifications include both Banners and Surveys. These are displayed based on iOS ViewControllers.

Every event occurs in the context of a ViewController. Every ViewController can be associated with some contextual data, which can be used as targeting rules for In-App Notifications.

Call the below show() Method in viewDidLoad method of every ViewController. show() Method should be called only once per ViewController.

  • iOS

        [notifyvisitors Show:DynamicTokens   CustomRule:CustomRule  ];   
        

Default values are passed as nil.

Dynamic Tokens (NSMutableDictionary)Dynamic tokens are used to show personalised content in Notification messages real time.

Custom Rules (NSMutableDictionary)This data can be used in configuring targeting rules for the Notifications.

Sample Code

  • iOS

        var DynamicTokens = [NSObject : AnyObject]()
                DynamicTokens["firstname"] = "Jhon"
                DynamicTokens["email"] = "jhon.123@gmail.com"
                var CustomRule =  [NSObject : AnyObject]()
                CustomRule["category"] = "fation"
                CustomRule["price"] = "2000"
                notifyvisitors.show(DynamicTokens, customRule: CustomRule)
        

If you are using UIScrollView call the following method in your ScrollViewDidScroll delegate method.

  • iOS

        func scrollViewDidScroll(scrollView: UIScrollView) {
        notifyvisitors.scrollViewDidScroll(scrollView)            }
        

Push Notifications

Add the following keys with their required values

  1. Add the following method in didFinishLaunchingWithOptions method of application.
  • iOS

        notifyvisitors.registerPush(withDelegate: self, app:
            application,launchOptions: launchOptions)
           
        
  1. Add the following methods inside your AppDelegate file to handle the registering and receiving events of push notification.
  • iOS

        func application(application: 
            UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
            notifyvisitors.DidRegisteredNotification(application, deviceToken: deviceToken)
                }
            func application(application: UIApplication, 
            didFailToRegisterForRemoteNotificationsWithError error: NSError) {   print(error)
            }
            func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [
            AnyHashable : Any]) {
            notifyvisitors.didReceiveRemoteNotification(userInfo: userInfo)
             }   
        
  1. For iOS 10 Push Notification, Add the following Delegate Methods in AppDelegate file.
  • Go to AppDelegate.h and import UserNotifications framework.
  • iOS

         import UserNotifications
                @UIApplicationMain
                class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
                } 
        
  • Go to AppDelegate.m file and add the following delegate methods
  • iOS

        @available(iOS 10.0,*)
            func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
                notifyvisitors.willPresent(notification, withCompletionHandler: completionHandler)
            }
            func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
                notifyvisitors.didReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
            }
            @available(iOS 10.0, *)
            func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
                notifyvisitors.didReceive(response)
            }
        
  • Add Notification Service Extension to support Rich media Attachment in iOS 10 push notification. Kindly refer to our Notification Service Extension creation guide.

Notification Center

You can show a list of push notifications received in an In-app Notification Center. Expiry of the notifications can be set from the panel.

To launch In-app notification center you can call the following method.

  • iOS

        notifyvisitors.NotifyVisitorsNotificationCentre() 
        

Geofencing

  1. To handle the geofencing notifications in background state and Inactive state of application, add the following codes in applicationDidEnterBackground and applicationDidBecomeActive methods respectively.
  • iOS

               func applicationDidEnterBackground(application: UIApplication) {
                notifyvisitors.NotifyVisitorsGeofencingApplicationDidEnterBackground()
                }
                func applicationDidBecomeActive(application: UIApplication) {
                notifyvisitors.NotifyVisitorsGeofencingapplicationDidBecomeActive()
                 }
        
  1. Add the following Code to receive local notification when geofencing events trigger.
  • iOS

        func application(_ application: UIApplication, didReceive notification:
            UILocalNotification)  { notifyvisitors.handleLocalNotifications(notification) }
        

Track Users

User API enables you to track a users' activity as they move from device to device and attach attributes to their profiles. Attributes enrich user profiles, like email, username, mobile, gender etc.This method should be called when the user is identified (mostly on login).

  • iOS

        notifyvisitors.UserIdentifier("userID", jsonData:
            jsonDataMutableDictionary)
        

USER_ID Setting the Unique ID is a critical piece to tie a user across devices and installs/uninstalls as well across all platforms (i.e. iOS, Android, Windows, The Web). Unique ID can be something like an email ID, a username (unique), or any Backend generated ID.

USER_ATTRIBUTES (jsonDataMutableDictionary) You can set the user attributes like name, email, mobile number. These can then be used to send personalised content in notifications. But these attributes can not be used in segmenting the users.

Default Attribute Names -

  • name
  • email
  • mobile

You can also pass your custom attributes like username, birthday, first name, last name.

IMPORTANT :

Attribute Names should contain only alpha-numerics, white spaces or ‘_’ ;
No other special characters are allowed.
Recommended names - ‘first_name’, ‘last_name’

Sample Code

  • iOS

        var userParameters = [NSObject : AnyObject]()
        userParameters["name"] = "Jhon"
        userParameters["email"] = "jhon.123@gmail.com"
        userParameters["mobile"] = "9818XXXXXX"
        notifyvisitors.UserIdentifier("userID", UserParams: userParameters)
 

Track Events

Event API enables you to record any actions your users perform, along with any properties that describe the action. These are then used for analytics, user segmentation or to trigger engagements or other actions.

  • iOS

         notifyvisitors.trackEvents:(”eventName” Attributes:AttributesDictionary< lifetimeValue:”Ltv” Scope:scope)
        
        

EVENT_NAME (string)Name of the event like sale, register. Event names should contain only alpha-numerics, white spaces or ‘_’ ; No other special characters are allowed.

EVENT_ATTRIBUTES (NSMutableDictionary)Attributes associated with the event. Attribute values should be passed in the form of Javascript strings, booleans and numbers respectively. Similarly date attribute values are expected in the form of Javascript date objects.

IMPORTANT :

Attribute Names should contain only alpha-numerics, white spaces or ‘_’ ; No other special characters are allowed. Recommended names - ‘category’, ‘price_usd’

LIFETIME_VALUE (integer)The score you would like to reward the user on performing this event like 10, 100.

SCOPE (integer) The scope of the event, whether it should be tracked every time it is called, or per session, or once in a lifetime. This parameter is used to minimise the duplication of data in analytics. It is an integer whose values are :

  1. Track every time the api is called
  2. Track once per session
  3. Track once in a lifetime

Sample Code

  • iOS

        
            var AttributesDictionary = [NSObject : AnyObject]()
            AttributesDictionary["price"] = "2000"
            AttributesDictionary["Category"] = "fancy"
            notifyvisitors.trackEvents("eventName", Attributes: AttributesDictionary,
            lifetimeValue:"100", Scope: 1)