iOS(Swift)

This guide provides step-by-step instructions on how to include the Conscent.ai Plugin in your iOS app. The Conscent.ai Plugin is developed in swift Language.

Pre-requisites

Conscent.ai iOS SDK supports iOS 13.0 and above.

Installation Steps

You can download the CCPlugin.xcframework File from here and add it to your project.

Make sure you change the embed mode for CCPlugin.xcframework to "Embed & Sign".

Initialize the SDK
  1. Import the CCPlugin framework into your ViewController class.

import CCPlugin
  1. In your ViewController class, configure the plugin by providing the client ID and the desired environment mode.

CCPlugin.shared.configure(mode: .sandbox, clientID: "your-client-id")
  • yourClientId - Pass your clientId received from Conscent.ai.

  • Mode - configuration testing of different environments available.

Api Mode can be set as :
   Mode.sandbox
   Mode.production
  1. You need to set the scrollDepth for the paywall by accessing the scrollDepth property of the CCPlugin.shared instance and modifying its value.

// Retrieve and set the scroll depth
let screenHeight = scrollView.bounds.height
let scrollDepth: Int = Int(scrollView.contentOffset.y)
CCplugin.shared.scrollDepth = scrollDepth
  1. You have to confirm UIScrollViewDelegate and you need to set scrollDepth and scrollDepthPercentage.

  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let scrollDepth: Int = Int(scrollView.contentOffset.y)
    CCplugin.shared.scrollDepth = scrollDepth
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
  func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    let contentHeight = scrollView.contentSize.height
    let scrollViewHeight = scrollView.bounds.height
    let scrollOffset = scrollView.contentOffset.y
    // Calculate the scroll percentage
    let scrollDepthPercentage = (scrollOffset / (contentHeight - scrollViewHeight)) * 100.0
    // Use the scrollPercentage as needed (e.g., update a label or send to analytics)
    print("Scroll Depth: \(scrollDepthPercentage)%")
    CCplugin.shared.scrollDepth = Int(scrollOffset)
    CCplugin.shared.scrollDepthPercentage = scrollDepthPercentage
  }
  1. You need to set the pageLength for the paywall by accessing the pageLength property of the CCPlugin.shared instance and modifying its value.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    debugPrint("pageLength:\(scrollView.contentSize.height)")
    CCplugin.shared.pageLength = Int(scrollView.contentSize.height)
  }

Enabling the debug mode:

The debugMode property of the CCPlugin.shared instance can be set to true or false to enable or disable debug mode. When debug mode is enabled, toasts will be shown if the content ID or client ID entered is incorrect. This is useful for development purposes.

CCplugin.shared.debugMode = false

Initialize the paywall

In order to ensure that the Conscent.ai Paywall appears on the targeted pages and the deep insights and analytics are collected optimally you need to implement the following method on all the content/article pages.

CCplugin.shared.showPayWall(contentID: contentID,
           title: contentID,
           categories: ["category1","category2","category3"] ,
           sections: ["section12","section14"],
           tags: ["premium"],
           contentUrl: "https://www.google.com/",
           authorName: "abc",
           parentView: view,
           eventParamsDelegate: self,
           googleLogInDelegate: self,
           completiondelegate: self
    )                                    

Parameters Description

contentID (string)

This will be your article or content id for which detail needs to be checked.

parentView

Pass the view on which you are going to show your content.

completionDelegate

This will be used to handle the success and failure cases. Pass the class as the delegate where you want to handle success or failure. This delegate is of the protocol CCPluginCompletionHandlerDelegate, which has three methods: purchasedOrNot(), onPaywallVisible(paywallType, paywallDisplayType, paywallHeight), and onCustomLinkSlot(link, contentId) that will be triggered in case of success and failure of the process.

subscriberDelegate(optional)

This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the subscription button is tapped. If you don't pass it in your delegate, it will not show the subscription view.

subscriberDelegate, which has one method: subscribeBtnTap() which will be triggered whenever the user clicks the Subscribe Button.

signInDelegate(optional)

This is an optional callback that will be called if you pass your class as its delegate. It will be triggered when the sign-in button is tapped. If you don't pass it in your delegate, it will not show the sign-in view.


signInDelegate, which has one method: signInTap() that will be triggered when the user clicks the signin button.

eventParamsDelegate(optional)

This will be used to get the events params. Pass the class as the delegate where you want to handle success. This delegate is of the protocol CCPluginEventParamsDelegate, which has methods: success(paywallId: String, contentId: String, paywallType: String, clientId: String, anonId: String) that will be triggered in case of google login click.

googleLogInDelegate(optional)

This will be used to trigger your Google sign. This delegate is of the protocol CCPluginGoogleLogInDelegate, which has methods: startGoogleLogin() that will be triggered in case of google login click.

Mandatory Step

  • In your Project go to your target and in the URL types add a new one with URL schemes "conscent".

  • This is important to handle redirection or app launches from the browser.

  • call below function inside of openURLContexts scene delegate(inbuilt in iOS).

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url {
       CCplugin.shared.handleRelaunchApp(url: url)
    }
}

You need to call CCplugin.shared.exitSDK() while leaving the scope of current controller.

override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)
    if parent == nil {
      // Back button action was triggered
      debugPrint("Back button pressed")
      CCplugin.shared.exitSDK()
    }
  }

Call the below function and pass the userId, after the user has logged in:

CCplugin.shared.setClientUserId(clientUserId: "Your_User_Id")
Login Functionality

Call this method to invoke our Login System

CCplugin.shared.onlyLoginFlow(  clientID: clientID, parentView: self.view)

Auto Login Functionality

The client can use his Login System using this functionality:

Generate token API is a post API that gets email, and phone number as body parameters and generates an auto login token.

  • username: API Key - present on conscent dashboard

  • password: API Secret - present on conscent dashboard

ConscentBaseUrl:

SANDBOX: https://sandbox-api.conscent.in
PRODUCTION:  https://api.conscent.in
fileprivate func autoLogIn(emailMobile: String?) {
        // Define the API endpoint URL
        if let apiURL = URL(string: "\(ConscentBaseUrl)/api/v1/client/generate-temp-token") {
            // Create the request object
            var request = URLRequest(url: apiURL)
            request.httpMethod = "POST"
            
            // Define the request body parameters (if any)
            var parameters: [String: Any] = [:]
            if let input = emailMobile, !input.isEmpty {
                if input.contains("@") {
                    parameters["email"] = input
                } else {
                    parameters["phoneNumber"] = input
                }
            }

            do {
                let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
                request.httpBody = jsonData
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            } catch {
                print("Error creating JSON data: \(error)")
                return
            }
            
            // Set the Basic Authentication header
                let username = "J1EFAQR-H0N4921-QCXKVNH-6W9ZYY9"
                let password = "CFR472795Q42TTQJFV84M37A5G4SJ1EFAQRH0N4921QCXKVNH6W9ZYY9"
                if let data = "\(username):\(password)".data(using: .utf8) {
                    let base64Credentials = data.base64EncodedString()
                    let authString = "Basic \(base64Credentials)"
                    request.addValue(authString, forHTTPHeaderField: "Authorization")
                }

            // Create a URLSession instance
            let session = URLSession.shared

            // Create the data task
            let task = session.dataTask(with: request)
            { (data, response, error) in
                // Check for any errors
                if let error = error {
                    print("Error: \(error)")
                    return
                }
                
                // Ensure there is a valid HTTP response
                guard let httpResponse = response as? HTTPURLResponse else {
                    print("Invalid response")
                    return
                }
                
                // Check the response status code
                if httpResponse.statusCode == 201 {
                    // Successful request
                    if let responseData = data {
                        // Process the response data
                        let responseString = String(data: responseData, encoding: .utf8)
                        print("Response: \(responseString ?? "")")
                        do {
                            if let json = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: AnyObject] {
                                if let tempAuthToken = json["tempAuthToken"] as? String {
                                    CCplugin.shared.configure(mode: .stage, clientID: "6336e56f047afa7cb875739e")
                                    CCplugin.shared.debugMode = true
                                    DispatchQueue.main.async {
                                        if let input = emailMobile, !input.isEmpty {
                                            if input.contains("@") {
                                                CCplugin.shared.autoLogIn(contentID: "Client-Story-Id-1", clientID: "6336e56f047afa7cb875739e", token: tempAuthToken, email: input, parentView: self.view, autoLogInDelegate: self)
                                            } else {
                                                CCplugin.shared.autoLogIn(contentID: "Client-Story-Id-1", clientID: "6336e56f047afa7cb875739e", token: tempAuthToken, phone: input, parentView: self.view, autoLogInDelegate: self)
                                            }
                                        }
                                    }
                                }
                            }
                        } catch let error {
                            print(error)
                        }
                    }
                } else {
                    // Request failed
                    print("Request failed: \(httpResponse.statusCode)")
                }
            }

            // Start the data task
            task.resume()
        }
    }

CCPluginAutoLogInDelegate:

This will be used to handle the success and failure cases. Pass the class as the delegate where you want to handle success or failure.

This delegate is of the protocol CCPluginAutoLogInDelegate, which has two methods:

autoLogInsuccess() and autoLogInfailure() that will be triggered in case of success and failure of the process.

CCPluginUserDetailsDelegate:

This delegate is of the protocol CCPluginUserDetailsDelegate, which has two methods:

success() and failure() that will be triggered in case of success and failure of the process.

extension AccountViewController: CCPluginUserDetailsDelegate {
    func success(userDetails: String) {
        debugPrint(userDetails)
        if let jsonData = userDetails.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    // Use the `json` object
                    if let phoneNumber = json["phoneNumber"] as? String {
                        Helper.userName = phoneNumber
                    } else if let email = json["email"] as? String {
                        Helper.userName = email
                    }
                }
            } catch {
                print("Error converting data to JSON: \(error)")
            }
        }
    }
    
    func failure(error: String) {
        debugPrint(error)
    }
}

Logout Functionality

CCPluginlogout:

Pass the class as the delegate where you want to handle success or failure.

This delegate is of the protocol CCPluginlogout, which has two methods:

success() and failure() that will be triggered in case of success and failure of the process.

CCplugin.shared.getlogout(logoutBtnDelegate: self)
extension AccountViewController: CCPluginlogout {
    func succes(successData: String) {
        debugPrint(successData)
    }
    
    func fail(error: String) {
        debugPrint(error)
    }
}

Last updated