Integration for SWIFT code


Follow the steps below

Download the sdk zip file which have some files library (.a file), header file (.h file), and an image (.png file), from sdk download link and include them into your project. Simply drag and include them in your project.

Download IOS SDK

1. Configure your info.plist

Open info.plist of your project as source code (right click on info.plist and click on Open as >> Source code) and add the following code in it.

Select All

    <key>NSAppTransportSecurity</key>
                 <dict>
        <key>NSAllowsArbitraryLoads</key>
              <true/>
               <key>NSExceptionDomains</key>
      <dict/>
        </dict>
        <key>UIBackgroundModes</key>
                <array>
                      <string>bluetooth-central</string>
                     <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/>-->
    

OR

You can simply open the info.plist and add the keys which works as same as above for this.

2. Initialise the SDK

Initialize the sdk in application didFinishLaunchingWithOptions function.

Define a String nvMode and set its value “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) as follows.

Select All

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

    

Add the following method in application didFinishLaunchingWithOptions to register your app for push notification and geofencing.

Select All

        notifyvisitors.registerPush(withDelegate: self, app: application, launchOptions: launchOptions)
    

Add the following three function inside your AppDelegate file to handle the registering and receiving events of push notification.


Select All

   
    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)
        }

    

iOS 10 Push Notification Handler

For iOS 10 Push Notification Add the following Delegate Methods in AppDelegate file.

Goto AppDelegate file import UserNotifications framework and also add UNUserNotificationCenterDelegate to support iOS 10 Push Notification or Rich media push notifications.

Select All

    import UserNotifications
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    }
    

Now add the following delegate methods into AppDelegate file to handle iOS 10 push notifications.

Select All

  
    @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 step 8 for Notification Service Extension creation guide.


Geofencing

To handle the geofencing notifications in background state and Inactive state of application add the following code in applicationDidEnterBackground and applicationDidBecomeActive respectively.


Select All

    func applicationDidEnterBackground(application: UIApplication) {
    notifyvisitors.NotifyVisitorsGeofencingApplicationDidEnterBackground()         }
    func applicationDidBecomeActive(application: UIApplication) {
     notifyvisitors.NotifyVisitorsGeofencingapplicationDidBecomeActive()             }

    

Add the following Code to receive local notification when geofencing events trigger.

Select All

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

Deep Linking

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

Select All

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

    

Give the Storyboard ID to all of your View Controller same as its name for example if you have a View Controller named HomeViewController then it's Stroryboard ID should be HomeViewController. Do it for all view controllers in storyboard.

3.Showing In-App Notifications

Use following function to show in app popups. Pass the User Token & CustomRule as NSMutableDictionary or pass nil.

Select All

    notifyvisitors.Show(UserToken , CustomRule:CustomRule )
    

Example:

Select All

    notifyvisitors.Show(nil  , CustomRule:nil  )     
    

OR

Select All

    notifyvisitors.Show(TokenMutableDictionary  , CustomRule:CustomRule  )
    

If you are using UIScrollView use the following function in your ScrollView delegate method ScrollViewDidScroll to View Notification on specific scroll position.

Select All


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

    

If you need to dismiss all inApp notifications currently viewing on screen, you can call DismissAllNotifyvisitorsInAppNotifications method like this:-

Select All

    notifyvisitors.DismissAllNotifyvisitorsInAppNotifications()
    

4. User Identifiers

To identify the different app users, call the method userIdentifier as follows.

Select All

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

5. Showing Notification Center

You can show list of push notification received push notifications in an In-app Notification Center. To launch In-app notification center you can call the following method.

Select All

    notifyvisitors.NotifyVisitorsNotificationCentre()
    

6. Tracking events

To track the various app events, call the method event like:-

Select All

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

Where:

eventName is the name of the event you want to track for example “sale”,
AttributesDictionaryis the json (Key Value Pair) containing different properties of the event in the form of json object like:-

Select All

   
    var AttributesDictionary = NSMutableDictionary (dictionary: dictionary)
    AttributesDictionary["price"] = "2000"  
    AttributesDictionary["Category"  ] = "fancy"  

    

Ltv is the value you want to give to user corresponding to every particular event.
scope - 1 (called every time the function is called)
scope -2(called once for the session)
scope -3 (called once per lifetime)


7. Handle Call to Action Manually

This point is optional if your apps action button action not working to load your app’s view controller you can handle it yourself using NSNotificationCenter to do that add the following code anywhere in your app recommended is inside viewDidLoad of first View Controller.

Select All

    NotificationCenter.default.addObserver(self, selector: #selector(self.triggerAction), name:NSNotification.Name(rawValue: "NVInAppViewConroller"), object: nil)
    

From above code your app will be notified on tap on action button if you set action button to open your in-app view controller on notifyvisitors control panel and now you can be able to handle the action as following method.

Select All

    @objc func triggerAction(notification: NSNotification){
    print("notification received  \(notification.userInfo)”)
    // Do your stuffs here………………………………………………………….. 
       }
    

8. Notification Service Extension

Create a Notification Service Extension in your project. To do that, in Xcode, select File >> New >> Target and choose the Notification Service Extension template.

Define a name for the Notification Service Extension as given below :

Once the target is created, Activate the scheme for Extension when prompted for the same. After this your extension will be added to project you will see a class with the extension name provided by you while creation and .plist file associated with it.

Now Open info.plist of your Notification Service Extension as source code (right click on info.plist and click on Open as >> Source code) and add the following code in it.

Select All

    <key>App Bundle identifier</key>
    <string>”Your App’s Project Identifier Name”</string>
    <key>NSExtension</key>
    <dict>
        <key>NSExtensionAttributes</key>
        <dict>
            <key>UNNotificationExtensionDefaultContentHidden</key>
            <true/>
            <key>UNNotificationExtensionInitialContentSizeRatio</key>
            <real>0.7</real>
        </dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.usernotifications.service</string>
        <key>NSExtensionPrincipalClass</key>
        <string>NotificationService</string>
    </dict>    
    
OR

You can simply open the info.plist and add the keys which works as same as above for this.

1.1Add a new row by going to the menu and clicking Editor > Add Item. Set a key App Bundle identifier as a String and set its value to your app’s Bundle Identifier.

1.2Expand the NSExtension and add NSExtensionAttributes as Dictionary. Inside NSExtensionAttributes dictionary add a key UNNotificationExtensionDefaultContentHidden as Boolean its value should be YES and add another key UNNotificationExtensionInitialContentSizeRatio as Number its value should be 0.7 as the following preview.

Goto Build Phase tab of your Notification Service Extension target and click on “+” sign under Link Binary With Libraries and click on “Add Other…” from promoted box and add the reference of our sdk .a file from your apps project folder (Don’t give reference of .a file from outside of your project).

Add a new header file and name it with following format. YOUR_EXTENSION_NAME-Bridging-Header.h in your Notification Service Extension. Example if your extension name is testExt. Then the header file name will be testExt-Bridging-Header.h. Now add the following import statement in YOUR_EXTENSION_NAME-Bridging-Header.h for accessing Native SDK Classes.

Select All

    #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_EXTENSION_NAME/YOUR_EXTENSION_NAME-Bridging-Header.h

Goto NotificationService.m file and update didReceiveRequestWithContentHandler delegate mehod as follows:

Select All

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        let userInfo: [AnyHashable: Any]? = request.content.userInfo
        if userInfo == nil {
            self.contentComplete()
            return
        }
        var FileData: [AnyHashable: Any] = notifyvisitors.getmediaInfo(userInfo)
        let FileUrl: String? = FileData["mediafile"] as? String
        let FileType: String? = FileData["filetype"] as? String
        if FileUrl == nil || FileType == nil {
            self.contentComplete()
            return
        }
notifyvisitors.getAttachmentData(forFileUrl: FileUrl, withFileType: FileType, completionHandler: {(attachment:UNNotificationAttachment?) ->Void in
            if (attachment != nil) {
    self.bestAttemptContent?.attachments = [attachment!]
            }
             self.contentComplete()
        })
    }
func contentComplete() {
    if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
        contentHandler(bestAttemptContent)
    }
}