Xamarin iOS

NugetNuget

📘

iOS 14 Implementation

In order to give you full control over the user experience, the Branch SDK will not trigger the IDFA permission modal.

However, we will still collect and use IDFAs when available if you do choose to trigger the modal.

LEARN MORE

❗️

Inconsistent Universal links behavior on iOS 11.2

After updating a device to iOS 11.2, we found that the app's AASA file is no longer downloaded reliably onto your user’s device after an app install. As a result, clicking on Universal links will no longer open the app consistenly. You can set forced uri redirect mode on your Branch links to open the app with URI schemes. View details of the issue on the Apple Bug report.

Configure Branch

Install Branch

NuGet

The Branch Xamarin SDK is available as a NuGet package. The Branch NuGet package must be added to each of the Xamarin projects that will use Branch methods.

To add the Branch NuGet package to a project:

  1. Right-click on each project and select Add > Add NuGet Packages
  2. Find the Branch Xamarin SDK package and add it to the project

Configure App

Create an Apple device Provisioning Profile for the app

  1. Open Xcode and create a new project with the same name as your Xamarin iOS project
  2. On the Xcode project's General tab, verify the app's case-sensitive Bundle Identifier is correct and select the appropriate Team (be sure to resolve any errors here)
  3. Select the Capabilities tab and enable the Associated Domains entitlement
  4. Create 'applinks:' entries for the Branch link domain and the alternate link domain (the link domain can be found at the bottom of the Branch dashboard's Link Settings page). For example, the entries for an app with the default link domain 'testiosapp.app.link' would be:
    applinks:testiosapp.app.link
    applinks:testiosapp-alternate.app.link
  5. Use Xcode to run this newly-created app on an iOS device. This will create and install a Provisioning Profile with the proper entitlements on that device.
  6. Close Xcode

Enter the app's settings on the Branch dashboard

  1. On the Link Settings page, check the I have an iOS App checkbox
  2. Enter the app's URI Scheme in the iOS URI Scheme field (for an app with the URI Scheme testbed-xamarin, for example, the entry would be: testbed-xamarin://)
  3. Enter the app's Apple Store name in the Apple Store Search field (if the app is not yet available on the App Store select Custom URL and enter as a placeholder the URL of an appropriate web site - the exact site does not matter)
  4. Check the Enable Universal Links checkbox
  5. Enter the app's case-sensitive Bundle Identifier and Apple App Prefix as shown on the Apple Developer Portal

Configure the Xamarin project's Info.plist file

  1. Open the Info.plist file
  2. Enter the app's Bundle Identifier from the Apple Developer Portal in the Bundle Identifier field. IMPORTANT: this field will automatically be populated with an all-lowercase value by Xamarin. The value is in fact case sensitive and must match the value in the Apple Developer Portal precisely.
  3. Click on the Advanced tab
  4. In the URL Types section, click the Add URL Type button
    Identifier: Branch Scheme
    URL Schemes: {the app's URI Scheme - 'testiosapp', for example} Role: Editor

imageimage

Configure the Xamarin project's Associated Domains entitlement

  1. Open the Entitlements.plist file and browse to Associated Domains
  2. Create entries for both the app's link domain and its alternate link domain. The entries for the TestBed-Xamarin app would be:
    applinks:testiosapp.app.link
    applinks:testiosapp-alternate.app.link

imageimage

Update the project's Signing Identity and Provisioning Profile

  1. Right-click on the iOS project and select Options
  2. Select iOS Bundle Signing
  3. Set the Signing Identity and Provisioning Profile values to the values used when deploying the Provisioning Profile to the device above

Initialize Branch

Branch initialization occurs within the FinishedLaunching method of the AppDelegate.cs file. Branch calls are also required in the OpenUrl, ContinueUserActivity, and ReceiveRemoteNotification methods to ensure that Branch link information is handled properly whenever the app becomes active.

Whenever the app becomes active, the Branch SDK will reach out to the Branch back end to retrieve any available link parameters. If the app became active due to a click on a Branch link, the link data will be returned in the InitSessionComplete method. This is where any deep link routing logic should reside. Any error in retrieving Branch link data from the back end will returned in the SessionRequestError method.

// AppDelegate.cs

using Foundation;
using UIKit;
using BranchXamarinSDK;
using BranchXamarinSDK.iOS;
using System;

namespace TestiOSApp.iOS
{
    [Register("AppDelegate")]
    public class AppDelegate : UIApplicationDelegate, IBranchBUOSessionInterface
    {
        public override UIWindow Window
        {
            get;
            set;
        }

        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Debug mode - set to 'false' before releasing to production
            BranchIOS.Debug = true;
            BranchIOS.Init("key_live_cgEguO4UiDJSL4HIyTu85dkkDAdz38ER", launchOptions, this);

            return true;
        }

        // Called when the app is opened via URI scheme
        public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            return BranchIOS.getInstance().OpenUrl(url);
        }

        // Called when the app is opened from a Universal Link
        public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity,
                      UIApplicationRestorationHandler completionHandler)
        {
            return BranchIOS.getInstance().ContinueUserActivity(userActivity);
        }

        // Called when the app receives a push notification
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            BranchIOS.getInstance().HandlePushNotification(userInfo);
        }

        // Called when the Branch initialization is completed
        // Put deep-linking logic in this method
        public void InitSessionComplete(BranchUniversalObject buo, BranchLinkProperties blp)
        {
            NSObject[] keys = {
                NSObject.FromObject("+is_first_session")
            };

            NSObject[] values = { NSObject.FromObject(0) };
            if (buo.metadata.ContainsKey("+is_first_session"))
            {
                values[0] = NSObject.FromObject(buo.metadata["+is_first_session"]);
            }

            NSDictionary nsData = NSDictionary.FromObjectsAndKeys(values, keys);
        }

        // Called when there is an error initializing Branch
        public void SessionRequestError(BranchError error)
        {
            Console.WriteLine("Branch error: " + error.ErrorCode);
            Console.WriteLine(error.ErrorMessage);
        }

    }
}

Configure Branch with Xamarin Forms

Add the Branch SDK with NuGet

The Branch Xamarin SDK is available as a NuGet package. The Branch NuGet package must be added to each of the Xamarin projects that will use Branch methods.

  1. Right-click on each project and select Add > Add NuGet Packages
  2. Find the Branch Xamarin SDK package and add it to the project

Create a class for Branch session handling

Branch initializes asynchronously, with Branch link parameters being returned following a network call to Branch. If initialization is successful, the InitSessionComplete method will be invoked. If initialization is unsuccessful, the SessionRequestError method will be invoked. Deep link routing logic should be located in the InitSessionComplete method.

  1. Right-click on the C# project and select Add > New File...
  2. Select: General > Empty Class
  3. Rename the file: TestXamarinFormsApp.cs
  4. Enter the following code (replacing 'TestXamarinFormsApp' with the actual name of the app):
using BranchXamarinSDK;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;

namespace TestXamarinFormsApp
{
    public class TestXamarinFormsApp : Application, IBranchSessionInterface
    {

        public TestXamarinFormsApp()
        {
        }

        #region IBranchSessionInterface implementation

        public void InitSessionComplete(Dictionary<string, object> data)
        {
        }

        public void CloseSessionComplete()
        {
        }

        public void SessionRequestError(BranchError error)
        {
        }

        #endregion
    }
}

Create a class for handling link data

Branch stores link data in an object referred to as the Branch Universal Object, or BUO.

  1. Right-click on the C# project and select Add > New File...
  2. Select: General > Empty Class
  3. Rename the file: TestXamarinFormsAppBUO.cs
  4. Enter the following code (replace 'TestXamarinFormsApp' with the actual name of the app):
using BranchXamarinSDK;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;

namespace TestXamarinFormsApp
{
    public class TestXamarinFormsAppBUO : Application, IBranchBUOSessionInterface
    {

        public TestXamarinFormsAppBUO()
        {
        }

        #region IBranchBUOSessionInterface implementation

        public void InitSessionComplete(BranchUniversalObject buo, BranchLinkProperties blp)
        {
        }

        public void SessionRequestError(BranchError error)
        {
        }

        #endregion
    }
}

Create an Apple device Provisioning Profile for the app

  1. Open Xcode and create a new project with the same name as your Xamarin iOS project
  2. On the Xcode project's General tab, enter the app's Bundle Identifier and select the appropriate Team (be sure to resolve any errors here)
  3. Select the Capabilities tab and enable the Associated Domains entitlement
  4. Create 'applinks:' entries for the Branch link domain assigned to the app (the link domain can be found at the bottom of the Branch dashboard's Link Settings page). For example, the entries for the app TestXamarinFormsApp would be:
    applinks:testxamarinformsapp.app.link
    applinks:testxamarinformsapp-alternate.app.link
  5. Use Xcode to run this newly-created app on an iOS device. This will create and install a Provisioning Profile with the proper entitlements on that device.
  6. Close Xcode

Enter the app's settings on the Branch dashboard

  1. On the Link Settings page, check the I have an iOS App checkbox
  2. Enter the app's URI Scheme in the iOS URI Scheme field (for an app with the URI Scheme testxamarinformsapp, for example, the entry would be: testxamarinformsapp://)
  3. Enter the app's Apple Store name in the Apple Store Search field (if the app is not yet available on the App Store select Custom URL and enter as a placeholder the URL of an appropriate web site - the exact site does not matter)
  4. Check the Enable Universal Links checkbox
  5. Enter the app's Bundle Identifier and Apple App Prefix as shown on the Apple Developer Portal

Configure the Xamarin project's Info.plist file

  1. Open the Info.plist file
  2. Enter the app's Bundle Identifier from the Apple Developer Portal in the Bundle Identifier field. IMPORTANT: this field will automatically be populated with an all-lowercase value by Xamarin. The value is in fact case sensitive and must match the value in the Apple Developer Portal precisely.
  3. Click on the Advanced tab
  4. In the URL Types section, click the Add URL Type button
    Identifier: Branch Scheme
    URL Schemes: {the app's URI Scheme - 'testxamarinformsapp', for example}
    Role: Editor

imageimage

Configure the Xamarin project's Associated Domains entitlement

  1. Open the Entitlements.plist file and browse to Associated Domains (if this file does not already exist, create it)
  2. Create entries for both the app's link domain and its alternate link domain. The entries for the TestBed-Xamarin app would be:
    applinks:testxamarinformsapp.app.link
    applinks:testxamarinformsapp-alternate.app.link

imageimage

Add Branch calls to the AppDelegate.cs file

To ensure that the Branch SDK initializes when the app starts and can retrieve link parameters whenever the app becomes active, Branch initialization occurs within the FinishedLaunching method of the AppDelegate.cs file. Branch calls are also required in the OpenUrl, ContinueUserActivity, and ReceiveRemoteNotification methods to ensure that Branch link information is handled properly whenever the app becomes active. The AppDelegate.cs file should look like this:

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;
using BranchXamarinSDK;
using TestXamarinFormsApp;

namespace TestXamarinFormsApp.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();

            // Debug mode - set to 'false' before releasing to production
            BranchIOS.Debug = true;

            TestXamarinFormsAppBUO appBUO = new TestXamarinFormsAppBUO();
            BranchIOS.Init("key_live_liAnF8k7gZUEZv76Rt9a4bffAzlC5zVW", options, appBUO);
            LoadApplication(appBUO);

            return base.FinishedLaunching(app, options);
        }

        // Called when the app is opened via URI scheme
        public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            return BranchIOS.getInstance().OpenUrl(url);
        }

        // Called when the app is opened from a Universal Link
        public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
        {
            return BranchIOS.getInstance().ContinueUserActivity(userActivity);
        }

        // Called when the app receives a push notification
        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            BranchIOS.getInstance().HandlePushNotification(userInfo);
        }
    }
}

Implement Features

Create content reference

BranchUniversalObject universalObject = new BranchUniversalObject();
universalObject.canonicalIdentifier = "id12345";
universalObject.title = "id12345 title";
universalObject.contentDescription = "My awesome piece of content!";
universalObject.imageUrl = "https://s3-us-west-1.amazonaws.com/branchhost/mosaic_og.png";
universalObject.metadata.AddCustomMetadata("foo", "bar");

Create deep link

BranchLinkProperties linkProperties = new BranchLinkProperties();
linkProperties.tags.Add("tag1");
linkProperties.tags.Add("tag2");
linkProperties.feature = "sharing";
linkProperties.channel = "facebook";
linkProperties.controlParams.Add("$desktop_url", "http://example.com");

Branch.GetInstance().GetShortURL(callback,
                                  universalObject,
                                  linkProperties);

Share deep link

  • Will generate a Branch deep link and tag it with the channel the user selects

  • Needs a Create content reference

  • Needs a [Create link reference]/developers-hub/docs/ios-advanced-features#section-create-link-reference)

  • Uses Deep Link Properties

Branch.GetInstance().ShareLink (callback,
           universalObject,
           linkProperties,
           message)

Read deep link

  • Retrieve Branch data from a deep link

  • Best practice to receive data from the listener (to prevent a race condition)

  • Returns deep link properties

// latest
Dictionary<string, object> sessionParams = Branch.GetInstance().GetLatestReferringParams();

// first
Dictionary<string, object> installParams = Branch.GetInstance().GetFirstReferringParams();

NativeLink™ Deferred Deep Linking (iOS Only)

  • Use iOS pasteboard to enable deferred deep linking via Branch NativeLink™

🚧

전제 조건

Make sure you are on v7.1.2+

To use this feature you must:

Implement one of the pasteboard opt-in options in the native iOS SDK code.

Track users

  • Sets the identity of a user (email, ID, UUID, etc) for events, deep links, and referrals

  • Validate with the Branch Dashboard

Branch branch = Branch.GetInstance ();
branch.SetIdentity("the user id", this);  // Where this implements IBranchIdentityInterface
branch.Logout(this); // Where this implements IBranchIdentityInterface

Track commerce events

  • Commerce Event는 사용자가 제품과 상호 작용하여 최종적으로 구매전환할 때까지 발생하는 일련의 행위들과 관련이 있습니다. 예를 들면 지불정보 추가, 구매 등이 있습니다. Branch Universal Ads(광고 어트리뷰션)를 활성화시킬 경우, 이러한 이벤트는 자동으로 특정 광고 파트너에 맵핑됩니다. 먼저 추적중인 이벤트와 연관된 각 제품에 해당되는 BranchUniversalLink를 생성하기 바랍니다.

  • From there, add the Branch Universal Object to the tracked event, and use the right predefined constant. For example, the code snippet below is to track when a user adds to cart, but simply replace that constant with another constant to track a different event.

  • A note on currency and exchange rates:
    If you track commerce events without a currency, we assume they are USD. If you track commerce events with a currency other than USD, we will convert the revenue specified to USD, using a recent exchange rate.

  • This allows you to easily visualize revenue on the Dashboard, across many countries and currencies, because all units are USD. The exchange rate is pulled from openexchangerates.org regularly, and is generally within an hour of the realtime exchange rate. If you view raw Branch events via either Webhooks or Exports, you can see the exchange rate used.

  • Validate with the Branch Dashboard

BranchUniversalObject universalObject = new BranchUniversalObject();
universalObject.canonicalIdentifier = "id12345";
universalObject.canonicalUrl = "https://branch.io/item/id12345";
universalObject.title = "Item 12345";
universalObject.contentDescription = "My awesome piece of content!";
universalObject.imageUrl = "https://s3-us-west-1.amazonaws.com/branchhost/mosaic_og.png";

universalObject.metadata.price = (float)23.20;
universalObject.metadata.quantity = 1;
universalObject.metadata.sku = "1994329302";
universalObject.metadata.productName = "my_product_name1";
universalObject.metadata.productBrand = "my_product_brand1";
universalObject.metadata.productCategory =                      BranchProductCategory.APPAREL_AND_ACCESSORIES;
universalObject.metadata.productVariant = "XL";
universalObject.metadata.condition = BranchCondition.NEW;
universalObject.metadata.AddCustomMetadata("foo", "bar");

BranchEvent branchCommerceEvent = new BranchEvent(BranchEventType.PURCHASE);
branchCommerceEvent.SetAlias("new_user_purchase");
branchCommerceEvent.AddContentItem(universalObject); 
branchCommerceEvent.SetRevenue((float)1.5);
branchCommerceEvent.SetShipping((float)10.5);
branchCommerceEvent.SetCurrency(BranchCurrencyType.USD);
branchCommerceEvent.SetTax((float)12.3);

Branch.GetInstance().SendEvent(branchCommerceEvent);

Track content events

  • Content Event는 사용자가 앱 내 콘텐츠에 대해 관심을 가지고 상호작용하는 행위를 취했을 때 전송하는 이벤트입니다. 예를 들면, 기사를 다루고 있는 앱에서 사용자가 콘텐츠를 검색하고, 읽고, 평가하고, 공유할 수 있습니다. 이는 블로그 게시물, 음악, 동영상, 사진, 전자상거래 카탈로그 항목 등 다양한 앱내 콘텐츠에 적용할 수 있습니다.

  • Validate with the Branch Dashboard

BranchEvent branchContentEvent = new BranchEvent(BranchEventType.SEARCH);
branchContentEvent.SetAlias("my_custom_alias");
branchContentEvent.SetDescription("Product Search");
branchContentEvent.SetSearchQuery("user search query terms for product xyz");
branchContentEvent.AddCustomData("content_event_property_key1", "content_event_property_val1");

Branch.GetInstance().SendEvent(branchContentEvent);

Track lifecycle events

  • Lifecycle Event는 사용자의 여정을 심화하기 위해 사용자가 단계별로 발생시키는 일련의 이벤트로 볼 수 있습니다. 이러한 이벤트는 사용자가 회원가입 또는 튜토리얼을 완료할 때 적용될 수 있고 게임 앱과 기타 유형의 앱에도 적용할 수 있습니다.

  • Validate with the Branch Dashboard

BranchEvent branchLifecycleEvent = new BranchEvent(BranchEventType.COMPLETE_REGISTRATION);
branchLifecycleEvent.SetAlias("registration_flow_xyz"); branchLifecycleEvent.SetDescription("Existing User Registration");
branchLifecycleEvent.AddCustomData("lifeycle_event_property_key1", "lifecycle_event_property_val1");

Branch.GetInstance().SendEvent(branchLifecycleEvent);

Track custom events

  • 사전 정의된 표준 이벤트가 아닌 임의로 정의한 이벤트를 추적하려면 아래 내용을 참고하시기 바랍니다.

  • Custom Event의 이벤트명은 문자, 숫자, 하이픈, 공백 및 밑줄만 포함한 40자 이하의 문자열을 사용할 것을 권장하고 하이픈으로 시작하지 않기 바랍니다. Facebook에서는 이러한 규칙을 위반하는 이벤트를 받아들이지 않을 것이고, Facebook 연동을 활성화하면, Branch에서 검증을 통해 유효하지 않는 이벤트를 수정할 수도 있습니다.

  • Validate with the Branch Dashboard

BranchEvent branchCustomEvent = new BranchEvent("custom_event");
 branchCustomEvent.SetAlias("custom_event_alias");
 branchCustomEvent.SetDescription("Custom Event Description");
 branchCustomEvent.AddCustomData("custom_event_property_key1", "custom_event_property_val1");
branchCustomEvent.AddCustomData("custom_event_property_key2", "custom_event_property_val2");

Branch.GetInstance().SendEvent(branchCustomEvent);

Troubleshoot Issues

Test deep link iOS

  • Create a deep link from the Branch Marketing Dashboard

  • Delete your app from the device

  • Compile your app with Xcode

  • Paste deep link in Apple Notes

  • Long press on the deep link (not 3D Touch)

  • Click Open in "APP_NAME" to open your app (example)

Unable to add Branch-required NuGet packages to the C# project

Adding required NuGet packages to the C# project may fail if the project has not been configured to use PCL 4.5 - Profile78

  1. Right-click on the project name and select: Options
  2. Browse the menu to Build > General
  3. Change the Current Profile to: PCL 4.5 - Profile78

Deploying iOS app to device fails with Provisioning Profile erros after changing entitlements

Xamarin automatically populates the Bundle Identifier field in the Info.plist file with an all-lowercase value derived from the app's name. This value is in fact case sensitive and must match the value in the Apple Developer Portal precisely. The default Xamarin configuration may work when there are no entitlements configured and then suddenly begin failing after entitlements have been added.

This issue can be resolved by ensuring that the Bundle Identifier in the Info.plist matches the Bundle Identifier shown on the Apple Developer Portal.

  1. Open the Info.plist file
  2. Enter the app's Bundle Identifier from the Apple Developer Portal in the Bundle Identifier field

Sample apps

There are four fully-functional demo apps included in this repository: a Xamarin Native and Xamarin Forms apps for both iOS and Android platforms. Use these apps as reference models for integrating the Branch SDK.

  • Testbed-Xamarin (Native apps)

  • Testbed-XamarinForms (Forms apps)


Recommended Next Steps
이 페이지가 도움이 되었습니까?