# iOS(Swift)

**Pre-requisites**

&#x20;Conscent.ai iOS SDK supports **iOS 13.0** and above.

<details>

<summary>Installation Steps</summary>

You can download the CCPlugin.xcframework File from [<mark style="color:orange;">`here`</mark>](https://github.com/tsbmediaventure/ConsCent-docs/blob/master/docs/mobile/IOS%20V2%20SDK/CCPlugin.xcframework.zip) and add it to your project.

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

</details>

<details>

<summary>Initialize the SDK</summary>

1. Import the CCPlugin framework into your ViewController class.

```swift
import CCPlugin
```

2. Configure the SDK in didFinishLaunchingWithOptions in AppDelegate class

```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // Configure the SDK
  CCPlugin.shared.configure(mode: .sandbox, clientID: "your-client-id")
  // ApplicationDelegate needs to be only called in case of Facebook Login
  ApplicationDelegate.shared.application(
                    application,
                    didFinishLaunchingWithOptions: launchOptions
                )
  // Additional configurations if necessary
  return true
}
```

* yourClientId - Pass your clientId received from Conscent.ai.
* Mode - configuration testing of different environments available.&#x20;

<pre class="language-swift"><code class="lang-swift"><strong>Api Mode can be set as :
</strong>   Mode.sandbox
   Mode.production
</code></pre>

3. You need to set the scrollDepth for the paywall by accessing the scrollDepth property of the CCPlugin.shared instance and modifying its value.

```swift
// Retrieve and set the scroll depth
let screenHeight = scrollView.bounds.height
let scrollDepth: Int = Int(scrollView.contentOffset.y)
CCplugin.shared.scrollDepth = scrollDepth
```

4. You have to confirm UIScrollViewDelegate and you need to set scrollDepth and scrollDepthPercentage.

```swift
  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
  }
```

5. You need to set the pageLength for the paywall by accessing the pageLength property of the CCPlugin.shared instance and modifying its value.

```swift
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.*

```swift
CCplugin.shared.debugMode = false
```

</details>

<details>

<summary>Initialize the paywall</summary>

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.

```swift
 CCplugin.shared.showPayWall(contentID: contentID,
                    variables: ["packageName":"cc.plugin.com", "device":"IOS"],
                    title: contentID,
                    categories: ["category1","category2","category3"] ,
                    sections: ["section12","section14"],
                    tags: ["premium"],
                    contentUrl: "https://www.google.com/",
                    authorName: "abc",
                    publicationDate: "2024-07-17T11:57:27.312Z",
                    parentView: view,
                    navigationController: self.navigationController,
                    eventParamsDelegate: self,
                    googleUserLogInDelegate: self,
                    completiondelegate: self,
                    signInDelegate: self
      )                                   
```

</details>

<details>

<summary>Google Login Process</summary>

1. To use Google login functionality you need to install pod in your project.

```swift
pod 'GoogleSignIn'
```

2. Add your OAuth client ID and custom URL scheme

Update your app's **Info.plist file** to add your OAuth client ID and a custom URL scheme based on the reversed client ID.

The reversed client ID is your client ID with the order of the dot-delimited fields reversed. This is also shown under "iOS URL scheme" when [selecting an existing iOS OAuth client in the Cloud console](https://console.cloud.google.com/apis/credentials?project=_). For example: com.googleusercontent.apps.1234567890-abcdefg

```swift
<key>GIDClientID</key>
<string>YOUR_IOS_CLIENT_ID</string>
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>YOUR_DOT_REVERSED_IOS_CLIENT_ID</string>
    </array>
  </dict>
</array>
```

3. To initiate a Google login

```swift
CCplugin.shared.configure(mode: .sandbox, clientID: clientID)
CCplugin.shared.googleUserLogIn(controller: self, googleUserLogInDelegate: self)
```

</details>

<details>

<summary>Facebook Login</summary>

1. To use Facebook login functionality you need to install a pod in your project.

```swift
pod 'FBSDKLoginKit', '17.4.0'
pod 'FBSDKShareKit', '17.4.0'
```

2. Update didFinishLaunchingWithOptions with the below code in Apthe pDelegate class.

```swift
 ApplicationDelegate.shared.application(
                    application,
                    didFinishLaunchingWithOptions: launchOptions
                )
```

3. To integrate Facebook Login into your iOS application, update your app's Info.plist file with the following entries. Replace the placeholders with the appropriate values from your Facebook app configuration.

Required Entries for Facebook Login

```swift
<key>FacebookAppID</key>
<string>YOUR_FACEBOOK_APP_ID</string>
<key>FacebookClientToken</key>
<string>YOUR_FACEBOOK_CLIENT_TOKEN</string>
<key>FacebookDisplayName</key>
<string>YOUR_FACEBOOK_APP_DISPLAY_NAME</string>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fbYOUR_FACEBOOK_APP_ID</string>
        </array>
    </dict>
</array>
```

</details>

| 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(accessTime), success(accessType), onPaywallVisible(paywallType, paywallDisplayType, paywallHeight),loginSuccess(message, userId, authToken), `failure(message)` |
| subscriberDelegate(optional)  | <p>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.</p><p>subscriberDelegate, which has one method: subscribeBtnTap() which will be triggered whenever the user clicks the Subscribe Button.</p>                               |
| signInDelegate(optional)      | <p>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. </p><p>signInDelegate, which has one method: signInTap() that will be triggered when the user clicks the signin button.</p>                                                          |
| 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).

<figure><img src="/files/BeOSswGXnZ7feoramcTk" alt=""><figcaption><p>Atached a screenshot for the reference:</p></figcaption></figure>

```swift
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.

```swift
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:**

```swift
CCplugin.shared.setClientUserId(clientUserId: "Your_User_Id")

```

<details>

<summary>Login Functionality</summary>

```swift
CCplugin.shared.configure(mode: .sandbox, clientID: clientID)
CCplugin.shared.userLogIn(userLogInDelegate: self)
```

**CCPluginUserLogInDelegate**

```swift
extension AccountViewController: CCPluginUserLogInDelegate {
  func userLogInSuccess(message: String, userId: String, authToken: String)
   {
    debugPrint("message: \(message), userId: \(userId), authToken: \(authToken)")
    }  
  func userLogInFailure(message: String, errorCode: String) {
        debugPrint(" message: \(message), errorCode: \(errorCode)")
        }
  func redirectToHomeScreen(message: String){
       debugPrint(" message: \(message)")
  }
}
```

</details>

**To enable Apple login follow either of these steps:**

**Xcode Steps:**

1. Open Xcode project.
2. Go to Target Settings → Signing & Capabilities.
3. Add "Sign in with Apple" capability.
4. Verify entitlements.
5. Ensure proper signing.

**App Store Connect Steps:**

1. Go to [App Store Connect](https://appstoreconnect.apple.com/).
2. Select the app under "My Apps."
3. Go to "App Information."
4. Add "Sign in with Apple" information (privacy policy and terms of service URLs).
5. Enable "Sign in with Apple."
6. Submit changes for review.

<details>

<summary>Fetch User-details</summary>

```swift
CCplugin.shared.openUserDetails(userProfileDelegate: self)
CCplugin.shared.getUserDetail(completiondelegate: self)
```

**CCPluginUserDetailsDelegate**

```swift
extension AccountViewController: CCPluginUserDetailsDelegate {
    func success(userDetails: CCPlugin.UserDetails) 
    {
    debugPrint("PhoneNo.: \(userDetails.phoneNumber ?? "") Email: \(userDetails.email ?? "") Name: \(userDetails.name ?? "")")     
    }
    
    func failure(message: String, errorCode: String) 
    {
    debugPrint(" message: \(message), errorCode: \(errorCode)")
    }
    func userProfileUpdated(message: String, statusCode: String)
    {
    debugPrint("Message: \(message) statusCode:\(statusCode)")
    }
}
```

**CCPluginUserProfileDelegate:**

**Note: Use these messages to handle Logout in UserProfile Logout.**

USER\_LOGOUT\_SUCCESS&#x20;

USER\_LOGOUT\_FAILED&#x20;

USER\_DELETE\_ACCOUNT\_SUCCESS&#x20;

USER\_DELETE\_ACCOUNT\_FAILED

```swift
extension AccountViewController: CCPluginUserProfileDelegate{
    func success(message: String, statusCode: String) {
        debugPrint("Message: \(message) statusCode:\(statusCode)")
    }
    
    func failure(message: String, errorCode: String) {
        debugPrint("Message: \(message) errorCode:\(errorCode)")
    }
    
}
```

</details>

<details>

<summary>Custom Logout Functionality </summary>

**Custom Logout Functionality** refers to a logout process that is specifically designed and implemented based on a client’s requirements

**CCPluginUserLogOutDelegate:**

Pass the class as the delegate where you want to handle success or failure.&#x20;

This delegate is of the protocol CCPluginlogout, which has two methods:&#x20;

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

```swift
CCplugin.shared.userLogout(userLogOutDelegate: self)
```

```swift
extension AccountViewController: CCPluginlogout {
    func userLogOutSuccess() {
        debugPrint("loginSuccess")
    }
    
 func userLogOutFailure(message: String, errorCode: String) {
        debugPrint(" \(message), \(errorCode)")
        
    }
}
```

</details>

**To use only the Subscription Landing Page, call the below method:**

```
CCplugin.shared.openCustomUrl(customUrl: String)
```

> CustomUrl is URL of the Subscription Landing Page with clientId.

### Demo APP [<mark style="color:orange;">Link</mark>](https://github.com/conscent-ai/Demo-Blog-IOS)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.conscent.ai/version-2.0/mobile-sdk/ios-swift.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
