{"id":21762113,"url":"https://github.com/segment-integrations/analytics-swift-engage","last_synced_at":"2025-10-07T19:30:48.763Z","repository":{"id":182648014,"uuid":"664745721","full_name":"segment-integrations/analytics-swift-engage","owner":"segment-integrations","description":null,"archived":false,"fork":false,"pushed_at":"2024-02-29T14:51:13.000Z","size":47,"stargazers_count":0,"open_issues_count":1,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-26T12:11:50.525Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/segment-integrations.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-10T16:47:04.000Z","updated_at":"2023-07-20T17:53:11.000Z","dependencies_parsed_at":"2023-11-14T17:40:52.478Z","dependency_job_id":"c6bf8e76-e545-4e1d-b2eb-3eb664ef8e07","html_url":"https://github.com/segment-integrations/analytics-swift-engage","commit_stats":null,"previous_names":["segment-integrations/analytics-swift-engage"],"tags_count":2,"template":false,"template_full_name":"segment-integrations/analytics-swift-destination-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segment-integrations%2Fanalytics-swift-engage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segment-integrations%2Fanalytics-swift-engage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segment-integrations%2Fanalytics-swift-engage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segment-integrations%2Fanalytics-swift-engage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/segment-integrations","download_url":"https://codeload.github.com/segment-integrations/analytics-swift-engage/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235652673,"owners_count":19024239,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-26T12:11:01.426Z","updated_at":"2025-10-07T19:30:43.392Z","avatar_url":"https://github.com/segment-integrations.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# Twilio Engage Plugin\n\n- [Twilio Engage Destination](#twilio-engage-destination)\n  - [Getting Started](#getting-started)\n  - [Subscription](#subscription)\n  - [Predefined Actions](#predefined-actions)\n  - [Default Notification Handling](#default-notification-handling)\n  - [Custom Notification Handling](#custom-notification-handling)\n  - [Handling Media](#handling-media)\n    - [Create Extension](#creating-the-extension)\n    - [Display Media](#displaying-media)\n  - [License](#license)\n\nThis plugin enables Segment's Analytics SDK to do push notification management with Twilio Engage.\n\n## Getting Started\n\nTo get started:\n1. follow the set up instructions for Analytics Swift [here](https://segment.com/docs/connections/sources/catalog/libraries/mobile/kotlin-android/#getting-started) \nto integrate Segment's Analytics SDK into your app. \n2. add the dependency: \n\n### via Xcode\nIn the Xcode `File` menu, click `Add Packages`.  You'll see a dialog where you can search for Swift packages.  In the search field, enter the URL to this repo.\n\n```\nhttps://github.com/segment-integrations/analytics-swift-engage\n```\n\nYou'll then have the option to pin to a version, or specific branch, as well as which project in your workspace to add it to.  Once you've made your selections, click the `Add Package` button.  \n\n### via Package.swift\n\nOpen your Package.swift file and add the following do your the `dependencies` section:\n\n```\n.package(\n            name: \"Segment\",\n            url: \"https://github.com/segment-integrations/analytics-swift-engage.git\",\n            from: \"1.1.2\"\n        ),\n```\n\n3. Import the Plugin in the file you configure your analytics instance: \n\n```\nimport Segment\nimport TwilioEngage // \u003c-- Add this line\n```\n\n4. Add an `engage` variable at the top of your `ApplicationDelegate`.\n\n```\n@main\nclass AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {\n    let engage = TwilioEngage { previous, current in\n        Tab1ViewController.addPush(s: \"Push Status Changed = \\(current)\")\n    }\n```\n\n5. Just under your Analytics-Swift library setup, call `analytics.add(plugin: ...)` to add an instance of the plugin to the Analytics timeline.\n\n```\nlet analytics = Analytics(configuration: Configuration(writeKey: \"\u003cYOUR WRITE KEY\u003e\")\n                    .flushAt(3)\n                    .trackApplicationLifecycleEvents(true))\n\nanalytics.add(plugin: engage)\n```\n\n6. Add the Following methods to your `AppDelegate` in order to start receiving and handling notifications \n\n**AppDelegate**\n\n```Swift\n   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -\u003e Bool {\n\n    //add the following:\n\n        let center  = UNUserNotificationCenter.current()\n        center.delegate = self\n        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in\n            guard granted else {\n                Analytics.main.declinedRemoteNotifications()\n                Tab1ViewController.addPush(s: \"User Declined Notifications\")\n                return\n            }\n            DispatchQueue.main.async {\n                UIApplication.shared.registerForRemoteNotifications()\n            }\n        }\n        \n        //Necessary in older versions of iOS.\n        if let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Codable] {\n            Tab1ViewController.addPush(s: \"App Launched via Notification \\(notification)\")\n            Analytics.main.receivedRemoteNotification(userInfo: notification)\n        }\n\n        ...\n\n        return true\n}\n\nfunc application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {\n    //Segment event to register for remote notifications\n    Analytics.main.registeredForRemoteNotifications(deviceToken: deviceToken)\n}\n\nfunc application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {\n    //Segment event for failure to register for remote notifications\n    Analytics.main.failedToRegisterForRemoteNotification(error: error)\n}\n\n    func userNotificationCenter(\n        _ center: UNUserNotificationCenter,\n        willPresent notification: UNNotification,\n        withCompletionHandler completionHandler:\n        @escaping (UNNotificationPresentationOptions) -\u003e Void\n    ) {\n        Analytics.main.receivedRemoteNotification(userInfo: userInfo)\n        \n        completionHandler([.banner, .sound, .badge])\n    }\n    \n    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -\u003e Void)\n    {\n        Analytics.main.receivedRemoteNotification(userInfo: userInfo)\n        \n        completionHandler()\n    }\n```\n\n## Subscription\n\nOnce the plugin is setup, it automatically tracks and updates push notification subscriptions \naccording to device's notification permissions. To listen to the subscription status changes, \nprovide a `StatusCallback` when initialize the plugin as following:\n```swift\nlet engage = TwilioEngage { previous, current in\n    //handle status updates \n    print(\"Push Status Changed /(current)\")\n}\n```\n\nOn iOS, three different statuses are tracked: `Subscribed`, `DidNotSubscribe`, `Unsubscribed`. \n* `Subscribed` is reported whenever app user toggles their device settings to allow push notification\n* `DidNotSubscribe` is reported in fresh start where no status has ever been reported\n* `Unsubscribed` is reported whenever user toggles their device settings to disable push notification and when the SDK fails to obtain a token from APNS\n\n## Predefined Actions\n\nTwilio Engage provides 4 predefined `tapActions` that you can handle however you see fit.\n* `open_app`: the app opens to the main view when the notification/button is on tapped.\n* `open_url`: the default browser opens a webview to the provided `link`\n* `deep_link`: the application routes to the provided `link`\n* `\u003ccustom_action\u003e`: a custom string which can be handled much like a deep-link depending on the use case.\n\n\n## Default Notification Handling\n\nHow you implement your push notification set up is entirely up to you. If you would prefer a \"standard\" implementation you can\nfollow the instructions in this section. The behavior of your notifications will follow the options outlined in the [Predefined Actions section above](#predefined-actions). If you would prefer to handle notifications in your own way, refer to the following section, Custom Notification Handling. \n\n1. Set the default notification categories inside the `didFinishinLaunchingWithOptions` method.\n\n```\n...\n    \nlet center  = UNUserNotificationCenter.current()\ncenter.delegate = self\n        \n//add default categories\nlet categories = engage.createDefaultCategories()\n        \nUNUserNotificationCenter.current()\n    .setNotificationCategories()\n```\n\n**Defining Custom Actions**\nYou can define custom actions/categories to work in addition to the default ones outlined in [Predefined Actions](#predefined-actions). \n\n```\nlet customCategory = TwilioEngage.CustomCategory(title: \"customized_push\", acceptActionTitle: \"Accept Title\", dismissActionTitle: \"Dismiss Title\")\n        \nlet categories = engage.createDefaultCategories(customCategory: customCategory)\n```\n\n2. Add the `handleNotification()` method to the `userNotificationCenter` `didReceive` method. \n\n```\nfunc userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -\u003e Void)\n{\n    let userInfo = response.notification.request.content.userInfo\n    Analytics.main.receivedRemoteNotification(userInfo: userInfo)\n\n    //engage method to handle default notifications \n    engage.handleNotificiation(response: response)\n    completionHandler()\n}\n```\n\n### Use the `Notification` extension to listen for `deep_links` and `custom_actions` \n\nSince it is not possible for the Twilio Engage plugin to automatically route deep-links or determine the logic of a custom action, t plugin includes a Notification extension you can use to listen for and handle these notification types. See the [example app for a complete implementation](https://github.com/segment-integrations/analytics-swift-engage/blob/main/Example/BasicExample/BasicExample/Tab1ViewController.swift).\n\n```\nNotification.Name.openButton.onPost { notification in\n    guard let deeplink = notification.userInfo?[\"link\"] as? String else {return}\n    print(\"Deep-link value: \\(deeplink)\")\n}\n```\n\n## Custom Notification Handling\nIf you need more control over your notifications, you can implement the handling and displaying in any way you see fit. Your analytics events will still be tracked, provided you have followed the general implementation steps outlined above. Examples for each of the predefined `tapActions` can be found below: \n\n**AppDelegate**\n\nWhen a push is received by a device the data is available in `userNotificationCenter: didReceive` (recieved in background) and `userNotificationCenter: willPresent` (recieved in foreground) in your AppDelegate.\n\n```Swift\nfunc userNotificationCenter(\n    _ center: UNUserNotificationCenter,\n    willPresent notification: UNNotification,\n    withCompletionHandler completionHandler:\n    @escaping (UNNotificationPresentationOptions) -\u003e Void\n) {\n    let userInfo = notification.request.content.userInfo\n    Tab1ViewController.addPush(s: \"Received in foreground: \\(userInfo)\")\n    Analytics.main.receivedRemoteNotification(userInfo: userInfo)\n        completionHandler([.banner, .sound, .badge])\n   }\n    \nfunc userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -\u003e Void)\n{\n    let userInfo = response.notification.request.content.userInfo\n    Tab1ViewController.addPush(s: \"Received in background: \\(userInfo)\")\n    Analytics.main.receivedRemoteNotification(userInfo: userInfo)\n\n    //add a custom method to handle the notification data \n    handleNotificiation(notification: userInfo, shouldAsk: true)\n    \n    completionHandler()\n}\n ...\n\n//an extension for logic for displaying different notification types: \nextension AppDelegate {\n\n  //Handle the notification based on the `tapAction`\n  func handleNotificiation(notification: [AnyHashable: Any], shouldAsk: Bool) {\n    if let aps = notification[\"aps\"] as? NSDictionary {\n      if let tapAction = aps[\"category\"] as? String {\n        switch tapAction {\n          case \"open_url\":\n            //add functionality for displaying a webview or opening a default browser \n          case \"deep_link\":\n            //add functionality for navigating to a specific screen in the app \n          case \"\u003ccustom_action\u003e\":\n            //handle a custom action like accept/decline or confirm/cancel  \n          default:\n            //this will catch `open_app` to open home screen\n            return\n        }\n      }\n    }\n  }\n}\n```\n\n## Handling Media\n\nIf you would like to display media in your push notifications, you will need to add a `NotificationService` extension to your app. Reference Apple's documentation for a more detailed overview of [UNNotificationServiceExtension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension).\n\n### Creating the Extension \n\n1. in Xcode, go to File -\u003e New -\u003e Target\n\u003cimg width=\"561\" alt=\"image\" src=\"https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/a95db4c4-dc21-4033-89a8-b88cf9cbbd2b\"\u003e\n\n2. search for the `Notification Service Extension`\n\u003cimg width=\"715\" alt=\"image\" src=\"https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/8d23555a-4431-4715-877b-52778e8e489d\"\u003e\n\n3. name the extension `\u003cYourAppName\u003eNotificationService\u003e` and finish the creation process.\n4. `\u003cYourAppName\u003eNotificationService/NotificationService\u003e` is where you can add custom logic to handle and display media.\n\n### Displaying Media\n**NotificationService `didRecieve` example**\n\n```swift\n    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -\u003e Void) {\n        self.contentHandler = contentHandler\n        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)\n        \n        if let bestAttemptContent = bestAttemptContent {\n            var urlString: String? = nil\n            let mediaArray: NSArray = bestAttemptContent.userInfo[\"media\"] as! NSArray\n            \n            if let mediaURLString = mediaArray[0] as? String {\n                urlString = mediaURLString\n            }\n            \n            if urlString != nil, let fileURL = URL(string: urlString!){\n                \n                guard let mediaData = NSData(contentsOf: fileURL) else {\n                    contentHandler(bestAttemptContent)\n                    return\n                }\n                \n                guard let mediaAttachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: \"engage-image.png\", data: mediaData, options: nil) else {\n                    contentHandler(bestAttemptContent)\n                    return\n                }\n                \n                bestAttemptContent.attachments = [ mediaAttachment ]\n            }\n            contentHandler(bestAttemptContent)\n        }\n        \n    }\n\n...\n\n//add an extension to `UNNotificationAttachment` to download/save the image \n@available(iOSApplicationExtension 10.0, *)\nextension UNNotificationAttachment {\n    \n    static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -\u003e UNNotificationAttachment? {\n        let fileManager = FileManager.default\n        let folderName = ProcessInfo.processInfo.globallyUniqueString\n        let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)\n        \n        do {\n            try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil)\n            let fileURL = folderURL?.appendingPathComponent(fileIdentifier)\n            try data.write(to: fileURL!, options: [])\n            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)\n            return attachment\n        } catch let error {\n            print(\"error \\(error)\")\n        }\n        \n        return nil\n    }\n}\n```\n\n## License\n```\nMIT License\n\nCopyright (c) 2021 Segment\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsegment-integrations%2Fanalytics-swift-engage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsegment-integrations%2Fanalytics-swift-engage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsegment-integrations%2Fanalytics-swift-engage/lists"}