MAUI Configuration
Integrate the Branch SDK into the iOS and Android components of your MAUI app.
1. Set Target Platforms
Update your project's target platforms:
- Open Visual Studio and right-click on your project, then select Properties → Build → Target Platforms.
- Check the Enable targeting the Android platform box and make sure the Target .NET Runtime is set to .NET 7.0 - also confirm you have the appropriate Target Android version and Minimum Android version set.
- Check the Enable targeting the iOS platform box and make sure the Target .NET Runtime is set to .NET 7.0 - also confirm you have the appropriate Target iOS version and Minimum iOS version set.
2. Install Branch NuGet Package
IMPORTANT: MAUI applications should use versions 9.0.0 or higher of the Branch-Xamarin-Linking-SDK
NuGet package - lower versions are for Xamarin applications.
To add the Branch NuGet package to your project:
- Right-click on your project and select Add → Add NuGet Packages.
- Find the
Branch-Xamarin-Linking-SDK
package and add it to the project. Make sure you are using version 9.0.0 or higher for a Xamarin application.
3. Configure App
iOS
1. Configure Branch Dashboard
Now that you have completed the general project setup requirements in Visual Studio, configure the iOS settings of your MAUI application in the Branch Dashboard:
- On the Configuration page, check the I have an iOS App checkbox.
- Enter the app's URI Scheme in the iOS URI Scheme field. For an app with the URI Scheme
MyMauiApp
, the entry would beMyMauiApp://
in the Dashboard. - Enter the app's Apple Store name in the Apple Store Search field. If the app is not yet available in the App Store, select Custom URL and enter the URL of an appropriate web site as a placeholder (the exact site does not matter).
- Check the Enable Universal Links checkbox and enter the app's case-sensitive Bundle ID, as well as Apple App Prefix as shown on the Apple Developer Portal.
2. Update Info.plist
File
Info.plist
File- Navigate to Project/Platforms/iOS/Info.plist, then right-click on the file and select Open With. Choose the editor you would like to use.
- Update your
Info.plist
file so it has theCFBundleIdentifier
andCFBundleURLTypes
keys, as shown in this sample file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>XSAppIconAssets</key>
<string>Assets.xcassets/appicon.appiconset</string>
<key>CFBundleIdentifier</key>
<string>io.Branch.MyMauiApp</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>MyMauiApp</string>
</array>
</dict>
</array>
</dict>
</plist>
3. Add Associated Domains in Entitlements.plist
Entitlements.plist
- If your project doesn't already have an
Entitlements.plist
file, add one now. Navigate to Project/Platforms/iOS, right-click on the iOS folder, then click Add → New File. Create an XML file with the nameEntitlements.plist
and save the file. - Once you have an
Entitlements.plist
file, edit it by right-clicking on the file, then select Open With and choose the editor you would like to use. - Add the
com.apple.developer.associated-domains
key, as well as an array that contains the Default Link Domain and Alternate Link Domain for your app, which can be found on the Branch Dashboard Configuration page. Make sure you prependapplinks:
to the beginning of each link in theEntitlements.plist
file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:h06h3.app.link</string>
<string>applinks:h06h3-alternate.app.link</string>
</array>
</dict>
</plist>
- Confirm the state of the
Entitlements.plist
file by using the Visual Studio entitlements editor. Do this by opening the file in Visual Studio and switching the view to Entitlements. Make sure the Associated Domains toggle is switched on and you see the relevant domains listed.
4. Configure Bundle Signing
- Make sure that your Apple Developer Account is associated with your solution. To do this, go to Tools → Preferences and sign in to your account.
- Right-click on your project, then navigate to Properties. Open the Bundle Signing section under iOS.
- In the Custom Entitlements field, add the path to the
Entitlements.plist
file you created. - Make sure the appropriate options are selected for Signing Identity and Provisioning Profile.
5. Update AppDelegate.cs
File
AppDelegate.cs
FileUse the following sample file to update your AppDelegate.cs
file to initialize Branch and turn on logging. Import the Branch SDK at the top of the file and replace key_live_<YOUR-GUID-HERE>
with your Branch key:
using BranchSDK;
using Foundation;
using UIKit;
namespace MyMauiApp;
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate, IBranchSessionInterface
{
protected override MauiApp CreateMauiApp() => MyMauiApp.MauiProgram.CreateMauiApp();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
Branch.EnableLogging = true;
BranchIOS.Init("key_live_<YOUR-GUIDE-HERE>", launchOptions, this);
return base.FinishedLaunching(application, launchOptions);
}
// Handle URI opens
public override bool OpenUrl(UIApplication application, NSUrl url, NSDictionary options)
{
return BranchIOS.getInstance().OpenUrl(url);
}
// Handle Universal Links
public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{
return BranchIOS.getInstance().ContinueUserActivity(userActivity);
}
public void InitSessionComplete(Dictionary<string, object> data)
{
LogMessage("InitSessionComplete: ");
foreach (var key in data.Keys)
{
LogMessage(key + " : " + data[key].ToString());
}
}
public void SessionRequestError(BranchError error)
{
LogMessage("SessionRequestError: ");
LogMessage("Error Message: " + error.ErrorMessage);
LogMessage("Error Code: " + error.ErrorCode);
}
void LogMessage(string message)
{
Console.WriteLine(message);
}
}
Android
1. Configure Branch Dashboard
Now that you have completed the general project setup requirements in Visual Studio, configure the Android settings of your MAUI application in the Branch Dashboard:
- On the Configuration page, check the I have an Android App checkbox.
- Enter the app's URI Scheme in the Android URI Scheme field. For an app with the URI Scheme
MyMauiApp
, the entry would beMyMauiApp://
in the Dashboard. - Enter the app's Apple Store name in the Google Play Search field. If the app is not yet available in Google Play, select Custom URL and enter the URL of an appropriate web site as a placeholder (the exact site does not matter).
- Enter your app's package name, which should match your
AndroidManifest.xml
file.
2. Update AndroidManifest.xml
File
AndroidManifest.xml
FileAlthough you have already set the minimum and target Android versions in your project's properties, you also need to do this in the AndroidManifest.xml
file. You also need to set your Branch key in the file:
- Navigate to Project/Platforms/Android/AndroidManifest.xml, then right-click on the file and select Open With. Choose the editor you would like to use.
- Use the following sample code to update your
AndroidManifest.xml
file. Add a<meta-data>
field for your Branch key and a<uses-sdk>
field for your minimum/target version values:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.Branch.MyMauiApp" android:versionCode="1" android:versionName="1.0">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:supportsRtl="true" android:label="MyMauiApp">
<meta-data android:name="io.branch.sdk.BranchKey" android:value="@string/branch_key" />
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="33" />
</manifest>
3. Add strings.xml
File
strings.xml
File- Navigate to Project/Platforms/Android/Resources/values, then right-click on the values folder and select Add → New File. Create an XML file with the name
strings.xml
and save the file. - Add the following code to your file, replacing
key_live_YOUR-GUID-HERE
with your Branch key from the Branch Dashboard:
<?xml version="1.0" encoding="UTF-8" ?>
<resources>
<string name="branch_key">key_live_YOUR-GUID-HERE</string>
</resources>
4. Update MainActivity.cs
File
MainActivity.cs
FileUse the following sample code to update the MainActivity
class in your MainActivity.cs
file. Give the Activity
a name, set a LaunchMode
, implement IBranchSessionInterface
, and replace key_live_YOUR-GUID-HERE
with your Branch key:
using Android.App;
using Android.Content.PM;
using Android.OS;
using BranchSDK;
using Android.Content;
namespace MyMauiApp;
[IntentFilter(new[] { "android.intent.action.VIEW" },
Categories = new[] { "android.intent.category.DEFAULT", "android.intent.category.BROWSABLE" },
DataScheme = "MyMauiApp",
DataHost = "open")]
[IntentFilter(new[] { "android.intent.action.VIEW" },
Categories = new[] { "android.intent.category.DEFAULT", "android.intent.category.BROWSABLE" },
DataScheme = "https",
DataHost = "MyMauiApp.app.link")]
/*
* Update the Activity
*
* Add a `Name` so this Activity can be located by name
* Set the `LaunchMode` (`SingleTop` or `SingleTask` is recommended)
*
* Implement `IBranchSessionInterface` to get Branch payloads
*
*/
[Activity(Name = "io.Branch.MyMauiApp.MainActivity", Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity, IBranchSessionInterface
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(saavedInstanceState);
BranchAndroid.Init(this, "key_live_<YOUR-GUID-HERE>", this);
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
intent.PutExtra("branch_force_new_session", true);
Intent = intent;
}
public void InitSessionComplete(Dictionary<string, object> data)
{
if (data == null)
{
LogMessage(" InitSessionComplete with data: null");
}
else
{
var dataString = string.Join(", ", data.Select(kvp => $"{kvp.Key}: {kvp.Value?.ToString() ?? "null"}"));
LogMessage($"InitSessionComplete with data: {dataString}");
}
}
public void SessionRequestError(BranchError error)
{
LogMessage("SessionRequestError: ");
LogMessage("Error Message: " + error.ErrorMessage);
LogMessage("Error Code: " + error.ErrorCode);
}
void LogMessage(string message)
{
Console.WriteLine(message);
}
}
5. Update MainApplication.cs
File
MainApplication.cs
FileUse the following sample code to add Branch initialization and logging to your MainApplication.cs
file:
using Android.App;
using Android.Runtime;
using BranchSDK;
namespace MyMauiApp;
[Application]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
public override void OnCreate()
{
base.OnCreate();
Branch.EnableLogging = true;
BranchAndroid.GetAutoInstance(ApplicationContext);
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
3. Send Branch Events
To start sending Branch Events, update your MainPage.xaml.cs
code to use the Branch SendEvent()
method:
using BranchSDK;
namespace MyMauiApp;
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
}
private void OnCounterClicked(object sender, EventArgs e)
{
count++;
if (count == 1)
CounterBtn.Text = $"Clicked {count} time";
else
CounterBtn.Text = $"Clicked {count} times";
SemanticScreenReader.Announce(CounterBtn.Text);
// Send Branch Test Event
SendEvent();
}
void SendEvent()
{
BranchEvent branchEvent = new BranchEvent(BranchEventType.PURCHASE);
branchEvent.SetAlias("new_user_purchase");
branchEvent.SetRevenue((float)1.5);
branchEvent.SetShipping((float)10.5);
branchEvent.SetCurrency(BranchCurrencyType.USD);
branchEvent.SetTax((float)12.3);
BranchUniversalObject buo1 = new BranchUniversalObject();
buo1.canonicalIdentifier = "id12345";
buo1.title = "id12345 title";
buo1.contentDescription = "ITEM 1";
BranchUniversalObject buo2 = new BranchUniversalObject();
buo2.canonicalIdentifier = "id12345";
buo2.title = "id12345 title";
buo2.contentDescription = "ITEM 2";
List<BranchUniversalObject> list = new List<BranchUniversalObject>();
list.Add(buo1);
list.Add(buo2);
branchEvent.AddContentItems(list);
Branch.GetInstance().SendEvent(branchEvent);
}
}
You can now create Branch Universal Objects and log various types of Branch Events.
4. Test
Test that your application is sending Branch Events as expected:
- Run the debug releases of your MAUI application on either an iOS or Android simulator within Visual Studio.
- Navigate to the Liveview page of your Branch Dashboard and start a new session.
- Go back to the simulator and perform the action that is meant to send the Branch Event.
- In the Branch Dashboard, filter the Branch Events by the type of Branch Event you are trying to log. The example on this page uses a
PURCHASE
Branch Event, which falls under the commerce event category. - You should see the Branch Events populate in the Branch Dashboard:
5. Troubleshoot
MAUI Sample Application
Full application: https://github.com/BranchMetrics/xamarin-branch-deep-linking-attribution/tree/master/Timber
iOS configuration: https://github.com/BranchMetrics/xamarin-branch-deep-linking-attribution/tree/master/Timber/Platforms/iOS
Android configuration: https://github.com/BranchMetrics/xamarin-branch-deep-linking-attribution/tree/master/Timber/Platforms/Android
Visual Studio
- Visual Studio aggressively caches build products, so make sure your build folder has no errors.
- Confirm you are using the correct Branch NuGet package. MAUI applications should use versions 9.0.0 or higher of the
Branch-Xamarin-Linking-SDK
NuGet package (lower versions are for Xamarin applications).
iOS
Issue | Solution |
---|---|
Universal links do not work | Your Entitlements.plist file is likely not set up correctly. Check the format, that it is included in Visual Studio, and the Apple account logged-in and associated with the project can manage signing. |
Integrity verification error | Causes app install to fail and means that the logged-in Apple Developer account does not have permission to sign for the app. Either switch accounts or request access from your organization. |
Android
Issue | Solution |
---|---|
"Unable to find BranchAndroid" | Use a .NET 7 test app because .NET 6 is unreliable about resolving it’s Android dependencies. |
Minimum version error | Make sure you have set an appropriate minimum version in both Project → Properties → Target Platforms as well as your AndroidManifest.xml file. |
JIN exception at runtime | Within MainApplication.cs , the BranchAndroid.GetAutoInstance(ApplicationContext) function fails with a JNI error. This can occur due to a missing Branch key. Set the key both programmatically and within the AndroidManifest.xml file. |
"Mismatch between instruction set variant of device" | App fails to run on device and error appears in logcat. To fix this, make sure you are using release builds for devices, not debug builds. |
"Installation of the app failed" | Make sure you are using debug builds for simulators, not release builds. |
Updated about 1 month ago