### Branch Initialization with Branch Key Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Provides an example of initializing the Branch SDK using a specific `branchKey`. This method is used when the `branch_key` is not set in the application's Plist file or when dynamically providing the key. ```Objective-C NSString *branchKey = @"YOUR_BRANCH_KEY"; [[Branch getInstance] initSessionWithBranchKey:branchKey andLaunchOptions:launchOptions]; ``` -------------------------------- ### Listing Content on Spotlight (Swift) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This code example illustrates how to better integrate your application's content with Apple Spotlight search. This feature was enhanced in version v0.21.3. Refer to the updated Spotlight documentation for detailed implementation instructions. ```swift import CoreSpotlight func indexContent() { let attributeSet = CSSearchableItemAttributeSet(itemContentType: "content") attributeSet.title = "My Item Title" attributeSet.contentDescription = "Description of my item." let item = CSSearchableItem(uniqueIdentifier: "unique_item_id", domainIdentifier: "my_domain", attributeSet: attributeSet) CSSearchableIndex.default().indexSearchableItems([item]) { (error) in if let error = error { print("Error indexing item: \(error.localizedDescription)") } else { print("Item indexed successfully") } } } ``` -------------------------------- ### Initialize Branch SDK in AppDelegate Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Initializes the Branch SDK within the AppDelegate for session tracking and deep link handling. This setup is crucial for receiving attribution data and processing incoming links. It includes enabling logging for debugging purposes and a handler for deep link parameters. ```objectivec // AppDelegate.m #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Enable logging for debugging (remove in production) [Branch enableLogging]; // Initialize Branch with deep link handler [[Branch getInstance] initSessionWithLaunchOptions:launchOptions andRegisterDeepLinkHandler:^(NSDictionary * _Nullable params, NSError * _Nullable error) { if (!error && params) { // Check if this is a Branch link click if ([[params objectForKey:BRANCH_INIT_KEY_CLICKED_BRANCH_LINK] boolValue]) { NSString *canonicalId = params[@"$canonical_identifier"]; NSString *title = params[@"$og_title"]; NSString *deepLinkPath = params[@"$deeplink_path"]; // Route to appropriate content NSLog(@"Deep link data: %@", params); } } }]; return YES; } // Handle Universal Links - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler { return [[Branch getInstance] continueUserActivity:userActivity]; } // Handle URL schemes - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { return [[Branch getInstance] application:app openURL:url options:options]; } ``` -------------------------------- ### Handle App Clips and Clipboard Support in Objective-C Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet shows how to integrate Branch SDK features for App Clips and clipboard-based deep linking. It includes setting the App Group for App Clips, enabling clipboard checking on install, determining if a clipboard toast will be shown, and supporting iOS 16+ UIPasteControl. ```objectivec #import // App Clip support - share data with full app [[Branch getInstance] setAppClipAppGroup:@"group.com.example.myapp"]; // Check for Branch links on clipboard (shows toast notification) // Call before initSession [[Branch getInstance] checkPasteboardOnInstall]; // Check if toast will be shown if ([[Branch getInstance] willShowPasteboardToast]) { NSLog(@"Branch will show clipboard toast on first launch"); } // iOS 16+ UIPasteControl support #if !TARGET_OS_TV if (@available(iOS 16, *)) { // When user taps UIPasteControl, pass items to Branch NSArray *itemProviders = pasteboard.itemProviders; [[Branch getInstance] passPasteItemProviders:itemProviders]; } #endif ``` -------------------------------- ### Validate SDK Integration in AppDelegate (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This code snippet demonstrates how to validate the Branch SDK integration by calling `validateSDKIntegration` within the `application:didFinishLaunchingWithOptions:` method of your app delegate. This is intended for development testing only and should be removed or commented out in release versions. Ensure you follow the instructions provided by the SDK for proper setup. ```objective-c [[Branch getInstance] validateSDKIntegration]; ``` -------------------------------- ### Track Commerce and Custom Events with Branch SDK (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet demonstrates how to track standard commerce events (Purchase, AddToCart, ViewItem, CompleteRegistration, ClickAd) and custom events using the Branch SDK in Objective-C. It covers setting transaction details, content items, currency, revenue, and custom data. The code includes examples for logging events with and without completion handlers. ```objectivec #import // Track a purchase event with full details BranchUniversalObject *product1 = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"sku/001"]; product1.title = @"Running Shoes"; product1.contentMetadata.price = [NSDecimalNumber decimalNumberWithString:@"129.99"]; product1.contentMetadata.quantity = 1; product1.contentMetadata.sku = @"RS-001"; BranchUniversalObject *product2 = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"sku/002"]; product2.title = @"Sports Socks"; product2.contentMetadata.price = [NSDecimalNumber decimalNumberWithString:@"19.99"]; product2.contentMetadata.quantity = 2; BranchEvent *purchaseEvent = [BranchEvent standardEvent:BranchStandardEventPurchase]; purchaseEvent.transactionID = @"TXN-2024-001234"; purchaseEvent.currency = BNCCurrencyUSD; purchaseEvent.revenue = [NSDecimalNumber decimalNumberWithString:@"169.97"]; purchaseEvent.shipping = [NSDecimalNumber decimalNumberWithString:@"9.99"]; purchaseEvent.tax = [NSDecimalNumber decimalNumberWithString:@"15.30"]; purchaseEvent.coupon = @"SUMMER20"; purchaseEvent.affiliation = @"mobile_app"; purchaseEvent.eventDescription = @"Summer sale purchase"; purchaseEvent.contentItems = @[product1, product2]; purchaseEvent.customData = @{ @"store_pickup": @"false", @"payment_method": @"apple_pay" }; // Log with completion handler [purchaseEvent logEventWithCompletion:^(BOOL success, NSError * _Nullable error) { if (success) { NSLog(@"Purchase event logged successfully"); } else { NSLog(@"Failed to log purchase: %@", error); } }]; // Track add to cart BranchEvent *addToCartEvent = [BranchEvent standardEvent:BranchStandardEventAddToCart withContentItem:product1]; addToCartEvent.currency = BNCCurrencyUSD; addToCartEvent.revenue = product1.contentMetadata.price; [addToCartEvent logEvent]; // Track content view BranchEvent *viewEvent = [BranchEvent standardEvent:BranchStandardEventViewItem withContentItem:product1]; viewEvent.searchQuery = @"running shoes"; [viewEvent logEvent]; // Track user registration BranchEvent *registrationEvent = [BranchEvent standardEvent:BranchStandardEventCompleteRegistration]; registrationEvent.eventDescription = @"User completed email registration"; registrationEvent.customData = @{ @"registration_method": @"email", @"newsletter_opt_in": @"true" }; [registrationEvent logEvent]; // Track custom event BranchEvent *customEvent = [BranchEvent customEventWithName:@"video_watched"]; customEvent.eventDescription = @"User watched product video"; customEvent.customData = @{ @"video_id": @"vid-12345", @"duration_seconds": @"120", @"completion_percent": @"85" }; [customEvent logEvent]; // Track ad events BranchEvent *adClickEvent = [BranchEvent standardEvent:BranchStandardEventClickAd]; adClickEvent.adType = BranchEventAdTypeBanner; adClickEvent.customData = @{@"ad_campaign": @"holiday_promo"}; [adClickEvent logEvent]; ``` -------------------------------- ### Getting Current ViewController (Objective-C Category) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This code snippet represents a category method `bnc_currentViewController` added to `UIViewController` in version v0.22.0. It provides a way to access the currently presented view controller, which can be useful for various SDK functionalities. ```objective-c // In UIViewController+Branch.h @interface UIViewController (Branch) - (UIViewController *)bnc_currentViewController; @end ``` -------------------------------- ### Get Last Attributed Touch Data with NSError (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Shows how to obtain the last attributed touch data, now including an NSError in the completion block for better error handling. This method is available in Objective-C and requires specifying an attribution window. ```objective-c - (void)lastAttributedTouchDataWithAttributionWindow:(NSInteger)window completion:(void(^) (BranchLastAttributedTouchData * _Nullable latd, NSError * _Nullable error))completion; ``` -------------------------------- ### Integrate Branch SDK with SceneDelegate (iOS 13+) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Integrates the Branch SDK using BranchScene for applications adopting the SceneDelegate architecture on iOS 13 and later. This handles deep links within the scene lifecycle, including URL contexts and user activities during cold starts. ```objectivec // SceneDelegate.m #import - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { [[BranchScene shared] initSessionWithLaunchOptions:nil registerDeepLinkHandler:^(NSDictionary * _Nullable params, NSError * _Nullable error, UIScene * _Nullable scene) { if (!error && params) { NSLog(@"Scene received deep link: %@", params); // Handle deep link routing } }]; // Handle URL contexts from cold start if (connectionOptions.URLContexts.count > 0) { [[BranchScene shared] scene:scene openURLContexts:connectionOptions.URLContexts]; } // Handle user activities from cold start if (connectionOptions.userActivities.count > 0) { for (NSUserActivity *activity in connectionOptions.userActivities) { [[BranchScene shared] scene:scene continueUserActivity:activity]; } } } - (void)scene:(UIScene *)scene openURLContexts:(NSSet *)URLContexts { [[BranchScene shared] scene:scene openURLContexts:URLContexts]; } - (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity { [[BranchScene shared] scene:scene continueUserActivity:userActivity]; } ``` -------------------------------- ### Set Test Branch Key (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Provides class methods to easily set and use a test Branch key. If `useTestBranchKey` is set to true, the SDK will attempt to use the 'test' key defined in the Info.plist file. This simplifies testing by allowing different Branch keys without recompiling. ```objective-c + (void)useTestBranchKey:(BOOL)useTestBranchKey; + (NSString *)branchKey; ``` -------------------------------- ### Handle URL Opening in iOS Applications Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md These Objective-C methods are used to handle incoming URLs, typically for deep linking functionality. They are essential for integrating SDKs that rely on URL schemes to launch or interact with the application. The methods differ slightly based on the iOS version and the availability of options dictionaries. ```Objective-C - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; ``` ```Objective-C - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options; ``` -------------------------------- ### Configure Branch Key Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Details the transition from `bnc_app_key` to `branch_key` for SDK configuration. Developers are advised to update their Plist files and initialization methods to use the new `branch_key`. This change aims to standardize authentication and configuration. ```Objective-C // Update in Plist: branch_key YOUR_BRANCH_KEY // Initialization example: [[Branch alloc] init]; // If branch_key is in Plist // or [[Branch getInstance] initSessionWithBranchKey:@"YOUR_BRANCH_KEY" andLaunchOptions:launchOptions]; ``` -------------------------------- ### Create and Register Branch Universal Object (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Demonstrates how to create a BranchUniversalObject to represent a product, set its metadata including e-commerce details and custom key-value pairs, and register a view event. This object is crucial for deep linking and content indexing. ```objectivec #import #import // Create a Branch Universal Object for a product BranchUniversalObject *buo = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"product/12345"]; buo.title = @"Premium Headphones"; buo.contentDescription = @"High-quality wireless headphones with noise cancellation"; buo.imageUrl = @"https://example.com/images/headphones.jpg"; buo.keywords = @[@"headphones", @"audio", @"wireless", @"premium"]; buo.publiclyIndex = YES; // Index on Google/Branch buo.locallyIndex = YES; // Index on Spotlight // Set content metadata for e-commerce buo.contentMetadata.contentSchema = BranchContentSchemaCommerceProduct; buo.contentMetadata.productName = @"Premium Headphones"; buo.contentMetadata.productBrand = @"AudioTech"; buo.contentMetadata.productCategory = BNCProductCategoryElectronics; buo.contentMetadata.price = [NSDecimalNumber decimalNumberWithString:@"299.99"]; buo.contentMetadata.currency = BNCCurrencyUSD; buo.contentMetadata.sku = @"AT-PH-001"; buo.contentMetadata.condition = BranchConditionNew; buo.contentMetadata.quantity = 1; buo.contentMetadata.ratingAverage = 4.8; buo.contentMetadata.ratingCount = 1250; // Add custom metadata buo.contentMetadata.customMetadata[@"color"] = @"black"; buo.contentMetadata.customMetadata[@"battery_life"] = @"30 hours"; // Register a content view event [buo registerViewWithCallback:^(NSDictionary * _Nullable params, NSError * _Nullable error) { if (error) { NSLog(@"Error registering view: %@", error); } }]; ``` -------------------------------- ### Configure Mock API URL for Branch SDK Testing Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This Objective-C code snippet demonstrates how to set a custom `branchAPIURL` for the `BNCPreferenceHelper`. This is useful for testing scenarios where you need to mock server responses using tools like WireMock. The property should be set before initializing the Branch SDK. ```Objective-C [[BNCPreferenceHelper preferenceHelper].branchAPIURL = @"http://localhost/branch-mock"; [[Branch getInstance] initSessionWithLaunchOptions:launchOptions]; ``` -------------------------------- ### Enabling v2-Event Support (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This code snippet shows how to enable v2-event support in the Branch SDK, a feature introduced in version v0.21.0. This allows for more advanced event tracking and data reporting. ```objective-c // Ensure v2 events are enabled in your Branch settings or via code if applicable. // Example: [[Branch getInstance] setUseV2EventAPI:YES]; ``` -------------------------------- ### Configure Branch SDK Logging and Debugging in Objective-C Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet demonstrates how to enable and configure logging for the Branch SDK. It covers basic logging, logging with specific levels and callbacks, and advanced logging that includes request and response data. It also shows how to set test Branch keys, validate SDK integration, and set custom API endpoints. ```objectivec #import #import // Enable logging (call before getInstance) [Branch enableLogging]; // Enable logging with specific level and callback [Branch enableLoggingAtLevel:BranchLogLevelDebug withCallback:^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { NSLog(@"Branch [%ld]: %@", (long)logLevel, message); }]; // Advanced logging with request/response data [Branch enableLoggingAtLevel:BranchLogLevelVerbose \ withAdvancedCallback:^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error, NSMutableURLRequest * _Nullable request, BNCServerResponse * _Nullable response) { NSLog(@"Branch request: %@", request.URL); NSLog(@"Branch response: %@", response.data); }]; // Use test Branch key (for development) [Branch setUseTestBranchKey:YES]; // Validate SDK integration [[Branch getInstance] validateSDKIntegration]; // Set custom API endpoints [Branch setAPIUrl:@"https://custom-api.example.com"]; // Use EU endpoints for data residency [[Branch getInstance] useEUEndpoints]; // Network configuration [[Branch getInstance] setRetryInterval:3.0]; // 3 seconds between retries [[Branch getInstance] setMaxRetries:5]; // Maximum 5 retries [[Branch getInstance] setNetworkTimeout:30.0]; // 30 second timeout // Set third-party API wait time [Branch setSDKWaitTimeForThirdPartyAPIs:1.0]; // 1 second // Check if URL is a Branch link if ([Branch isBranchLink:@"https://example.app.link/abc123"]) { NSLog(@"This is a Branch link"); } // Set request metadata (included in all requests) [[Branch getInstance] setRequestMetadataKey:@"app_version" value:@"2.1.0"]; [[Branch getInstance] setRequestMetadataKey:@"user_tier" value:@"premium"]; // Add partner parameters [[Branch getInstance] addFacebookPartnerParameterWithName:@"em" value:@"hashed_email"]; [[Branch getInstance] addSnapPartnerParameterWithName:@"hashed_email" value:@"abc123"]; // Clear partner parameters [[Branch getInstance] clearPartnerParameters]; // Debug mode - add constant params to responses [[Branch getInstance] setDeepLinkDebugMode:@{@"test_key": @"test_value"}]; // Set allowed URL schemes [[Branch getInstance] setAllowedSchemes:@[@"https", @"myapp"]]; ``` -------------------------------- ### Handle Scheme-Based URLs from App Delegate (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Adds two new methods to the Branch SDK for handling scheme-based URLs originating from the application delegate. These methods mirror the UIApplicationDelegate methods, providing the SDK with enhanced flexibility in processing incoming URLs. This is crucial for deep linking functionality. ```objective-c application:openURL:sourceApplication:annotation:annotation ``` -------------------------------- ### Generate Trackable Short URLs with Branch SDK (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Demonstrates how to generate trackable short URLs using the Branch iOS SDK. It covers asynchronous and synchronous methods for URL generation, as well as direct URL creation from a Branch instance. This method is useful for sharing content across various channels. ```objectivec #import #import #import // Setup content and link properties BranchUniversalObject *buo = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"article/789"]; buo.title = @"10 Tips for Better Sleep"; buo.contentDescription = @"Expert advice on improving your sleep quality"; BranchLinkProperties *lp = [[BranchLinkProperties alloc] init]; lp.feature = @"content_share"; lp.channel = @"twitter"; // Asynchronous URL generation (recommended) [buo getShortUrlWithLinkProperties:lp andCallback:^(NSString * _Nullable url, NSError * _Nullable error) { if (!error && url) { NSLog(@"Generated Branch URL: %@", url); // Share the URL [self shareURL:url]; } else { NSLog(@"Error generating URL: %@", error); } }]; // Synchronous URL generation (blocks thread) NSString *syncUrl = [buo getShortUrlWithLinkProperties:lp]; // Direct URL generation from Branch instance [[Branch getInstance] getShortURLWithParams:@{ @"product_id": @"12345", @"discount": @"20%", @"$og_title": @"Special Offer" } andChannel:@"email" andFeature:@"promo" andStage:@"checkout" andCallback:^(NSString * _Nullable url, NSError * _Nullable error) { if (url) { NSLog(@"Promo URL: %@", url); } }]; // Generate long URL (no network request needed) NSString *longUrl = [[Branch getInstance] getLongURLWithParams:@{@"item": @"123"} andChannel:@"sms" andTags:@[@"urgent"] andFeature:@"notification" andStage:@"reminder" andAlias:nil]; ``` -------------------------------- ### Register Deep Link Controller API (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Introduces a new method for registering deep link controllers with presentation options and deprecates the older version. This allows for more control over how deep links are presented to the user. It is recommended to use the new API for better flexibility. ```objective-c - (void)registerDeepLinkController:(UIViewController *)controller forKey:(NSString *)key withPresentation:(BNCViewControllerPresentationOption)option; - (void)registerDeepLinkController:(UIViewController *)controller forKey:(NSString *)key; ``` -------------------------------- ### Set Custom URI Scheme Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Explains how to set a custom URI scheme for the Branch SDK. Developers can now explicitly define their scheme using `setUriScheme:@"myapp://"`. The SDK also maintains backward compatibility with previous behaviors for a transition period. ```Objective-C // Set custom URI scheme [[Branch getInstance] setUriScheme:@"myapp://"]; ``` -------------------------------- ### Handling Branch Session Notifications (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This snippet shows how to register for and handle Branch session notifications, specifically `BranchWillStartSessionNotification` and `BranchDidStartSessionNotification`. These notifications were added in version v0.21.3 to provide insights into the session lifecycle. ```objective-c [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(branchSessionStarted:) name:BranchDidStartSessionNotification object:nil]; - (void)branchSessionStarted:(NSNotification *)notification { // Handle session start event } ``` -------------------------------- ### Generate Customizable QR Codes with Branch (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet shows how to generate Branch QR codes with customizable visual appearances. It covers creating a BranchUniversalObject and BranchLinkProperties, configuring QR code properties like color, logo, and size, and then retrieving the QR code as a UIImage or NSData. It also demonstrates how to present the QR code in a share sheet. ```objectivec #import // Create content for QR code BranchUniversalObject *buo = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"menu/restaurant-123"]; buo.title = @"Restaurant Menu"; BranchLinkProperties *lp = [[BranchLinkProperties alloc] init]; lp.feature = @"qr_code"; lp.channel = @"in_store"; lp.campaign = @"table_menu"; // Configure QR code appearance BranchQRCode *qrCode = [[BranchQRCode alloc] init]; qrCode.codeColor = [UIColor blackColor]; qrCode.backgroundColor = [UIColor whiteColor]; qrCode.centerLogo = @"https://example.com/logo.png"; qrCode.width = @(500); // 500px qrCode.margin = @(2); // 2px border qrCode.imageFormat = BranchQRCodeImageFormatPNG; // Get QR code as UIImage [qrCode getQRCodeAsImage:buo linkProperties:lp completion:^(UIImage * _Nullable qrCodeImage, NSError * _Nullable error) { if (qrCodeImage) { self.qrCodeImageView.image = qrCodeImage; } else { NSLog(@"QR Code error: %@", error); } }]; // Get QR code as NSData (for saving/sending) [qrCode getQRCodeAsData:buo linkProperties:lp completion:^(NSData * _Nullable qrCodeData, NSError * _Nullable error) { if (qrCodeData) { // Save to file or upload [qrCodeData writeToFile:@"/path/to/qrcode.png" atomically:YES]; } }]; // Show QR code in share sheet [qrCode showShareSheetWithQRCodeFromViewController:self anchor:nil universalObject:buo linkProperties:lp completion:^(NSError * _Nullable error) { if (error) { NSLog(@"Share QR error: %@", error); } }]; ``` -------------------------------- ### Manage User Identity with Branch SDK (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet demonstrates how to set and clear user identities, check if a user is identified, and retrieve referring parameters for attribution analysis. It requires the Branch SDK and handles user login/logout events. ```objectivec #import // Set user identity when user logs in - (void)userDidLogin:(NSString *)userId { [[Branch getInstance] setIdentity:userId withCallback:^(NSDictionary * _Nullable params, NSError * _Nullable error) { if (!error) { NSLog(@"User identified: %@", userId); // User's previous sessions are now linked } else { NSLog(@"Identity error: %@", error); } }]; } // Logout user (clears identity) - (void)userDidLogout { [[Branch getInstance] logoutWithCallback:^(BOOL changed, NSError * _Nullable error) { if (changed) { NSLog(@"User logged out successfully"); } else { NSLog(@"Logout error: %@", error); } }]; } // Check if user is identified if ([[Branch getInstance] isUserIdentified]) { NSLog(@"User has a custom identity"); } // Get first referring parameters (from initial install/open) NSDictionary *firstParams = [[Branch getInstance] getFirstReferringParams]; BranchUniversalObject *firstBUO = [[Branch getInstance] getFirstReferringBranchUniversalObject]; BranchLinkProperties *firstLP = [[Branch getInstance] getFirstReferringBranchLinkProperties]; // Get latest referring parameters (from most recent link click) NSDictionary *latestParams = [[Branch getInstance] getLatestReferringParams]; BranchUniversalObject *latestBUO = [[Branch getInstance] getLatestReferringBranchUniversalObject]; // Get synchronous (blocking) latest params NSDictionary *syncParams = [[Branch getInstance] getLatestReferringParamsSynchronous]; ``` -------------------------------- ### Index Content for iOS Spotlight Search with Branch SDK (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet shows how to index individual or multiple app content items for iOS Spotlight search using the Branch SDK. It allows users to discover app content directly from Spotlight and deep link into specific items. Dependencies include Branch SDK and BranchUniversalObject. Functionality covers indexing, removing single items, and removing all Branch content. ```objectivec #import #import // Index a single item on Spotlight BranchUniversalObject *article = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"article/tech-trends-2024"]; article.title = @"Tech Trends 2024"; article.contentDescription = @"Top technology trends to watch this year"; article.imageUrl = @"https://example.com/tech-trends.jpg"; article.keywords = @[@"technology", @"trends", @"2024", @"innovation"]; article.locallyIndex = YES; BranchLinkProperties *lp = [[BranchLinkProperties alloc] init]; lp.feature = @"spotlight"; // List on Spotlight [article listOnSpotlightWithLinkProperties:lp callback:^(NSString * _Nullable url, NSError * _Nullable error) { if (url) { NSLog(@"Indexed on Spotlight with URL: %@", url); } }]; // Index multiple items at once NSArray *articles = @[article1, article2, article3]; [[Branch getInstance] indexOnSpotlightUsingSearchableItems:articles completion:^(NSArray * _Nonnull universalObjects, NSError * _Nullable error) { if (!error) { for (BranchUniversalObject *obj in universalObjects) { NSLog(@"Indexed: %@ with ID: %@", obj.title, obj.canonicalIdentifier); } } }]; // Remove from Spotlight [article removeFromSpotlightWithCallback:^(NSError * _Nullable error) { if (!error) { NSLog(@"Removed from Spotlight"); } }]; // Remove all Branch content from Spotlight [[Branch getInstance] removeAllPrivateContentFromSpotLightWithCallback:^(NSError * _Nullable error) { if (!error) { NSLog(@"All content removed from Spotlight"); } }]; ``` -------------------------------- ### Share Native Sheets with Branch Deep Links (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This snippet demonstrates how to present native iOS share sheets with Branch deep links. It covers creating a BranchUniversalObject, configuring BranchLinkProperties, and using BranchShareLink for a customized sharing experience. It also shows how to use BranchUniversalObject directly and integrate with UIActivityViewController using BranchActivityItemProvider. ```objectivec #import // Create content object BranchUniversalObject *buo = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"recipe/pasta-carbonara"]; buo.title = @"Classic Pasta Carbonara"; buo.contentDescription = @"Learn to make authentic Italian carbonara"; buo.imageUrl = @"https://example.com/carbonara.jpg"; BranchLinkProperties *lp = [[BranchLinkProperties alloc] init]; lp.feature = @"sharing"; // Method 1: Using BranchShareLink (recommended) BranchShareLink *shareLink = [[BranchShareLink alloc] initWithUniversalObject:buo linkProperties:lp]; shareLink.title = @"Share Recipe"; shareLink.shareText = @"Check out this amazing carbonara recipe!"; shareLink.emailSubject = @"Recipe: Classic Pasta Carbonara"; // Add iOS 13+ link preview metadata if (@available(iOS 13.0, *)) { UIImage *previewIcon = [UIImage imageNamed:@"recipe_icon"]; [shareLink addLPLinkMetadata:@"Pasta Carbonara Recipe" icon:previewIcon]; } // Set delegate for customization shareLink.delegate = self; // Present share sheet [shareLink presentActivityViewControllerFromViewController:self anchor:sender]; // Handle completion shareLink.completionError = ^(NSString * _Nullable activityType, BOOL completed, NSError * _Nullable error) { if (completed) { NSLog(@"Successfully shared via: %@", activityType); } else if (error) { NSLog(@"Share error: %@", error); } }; // Method 2: Using BranchUniversalObject directly [buo showShareSheetWithLinkProperties:lp andShareText:@"Amazing recipe!" fromViewController:self completionWithError:^(NSString * _Nullable activityType, BOOL completed, NSError * _Nullable error) { NSLog(@"Share completed: %d, activity: %@", completed, activityType); }]; // Method 3: Using UIActivityViewController with BranchActivityItemProvider UIActivityItemProvider *branchItem = [Branch getBranchActivityItemWithParams:@{ @"recipe_id": @"carbonara-001", @"$og_title": @"Classic Pasta Carbonara" } feature:@"sharing" stage:@"recipe_detail" tags:@[@"recipe", @"italian"]]; UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[branchItem, @"Check out this recipe!"] applicationActivities:nil]; [self presentViewController:activityVC animated:YES completion:nil]; ``` -------------------------------- ### Expose isUserIdentified Method Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Introduces the `isUserIdentified` method to allow developers to check if Branch has a User Identity set. This helps in understanding the SDK's current state regarding user identification. ```Objective-C BOOL isIdentified = [[Branch getInstance] isUserIdentified]; ``` -------------------------------- ### Set Debugging Instance Method Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Deprecates the static usage of `setDebug`. Developers should now use the instance method for setting debug mode, improving encapsulation and testability. This change is part of internal cleanup and better debugging practices. ```Objective-C // Deprecated: [Branch setDebug:YES]; // Recommended: [[Branch getInstance] setDebug:YES]; ``` -------------------------------- ### Configure Branch Link Properties (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Illustrates how to configure BranchLinkProperties to customize deep link behavior, including setting sharing parameters, campaign details, and control parameters for routing. These properties are essential for controlling how users are directed and what data is passed upon deep linking. ```objectivec #import // Create link properties for a sharing campaign BranchLinkProperties *linkProperties = [[BranchLinkProperties alloc] init]; linkProperties.feature = @"sharing"; linkProperties.channel = @"facebook"; linkProperties.campaign = @"summer_sale_2024"; linkProperties.stage = @"product_detail"; linkProperties.tags = @[@"premium", @"electronics", @"sale"]; linkProperties.alias = @"headphones-deal"; // Custom URL alias (must be unique) linkProperties.matchDuration = 7200; // 2 hours match window for deferred deep linking // Add control parameters for routing [linkProperties addControlParam:@"$desktop_url" withValue:@"https://example.com/headphones"]; [linkProperties addControlParam:@"$ios_url" withValue:@"myapp://product/12345"]; [linkProperties addControlParam:@"$android_url" withValue:@"myapp://product/12345"]; [linkProperties addControlParam:@"$fallback_url" withValue:@"https://example.com/app-download"]; [linkProperties addControlParam:@"$deeplink_path" withValue:@"product/12345"]; [linkProperties addControlParam:@"$og_title" withValue:@"Check out these headphones!"]; [linkProperties addControlParam:@"$og_description" withValue:@"Premium wireless headphones on sale"]; [linkProperties addControlParam:@"$og_image_url" withValue:@"https://example.com/og-image.jpg"]; ``` -------------------------------- ### Add LPLinkMetadata to Share Sheets (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md Demonstrates how to add LPLinkMetadata to share sheets using Objective-C. This requires iOS 13.0 or later. It involves creating an LPLinkMetadata object, setting its title, and providing an icon and image using NSItemProvider. ```objective-c // LPLinkMetadata example if (@available(iOS 13.0, macCatalyst 13.0, *)) { LPLinkMetadata *tempLinkMetatData = [[LPLinkMetadata alloc] init]; tempLinkMetatData.title = @"Branch URL"; UIImage *img = [UIImage imageNamed:@"Brand Assets"]; tempLinkMetatData.iconProvider = [[NSItemProvider alloc] initWithObject:img]; tempLinkMetatData.imageProvider = [[NSItemProvider alloc] initWithObject:img]; shareLink.lpMetaData = tempLinkMetatData; } ``` -------------------------------- ### Deeplink Routing Validation (URL Parameter) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md To test and verify if your Branch links are correctly routing users to the intended content, append `validate=true` to your Branch links. This feature helps in debugging deeplink functionality. More information can be found in the Branch SDK documentation regarding validation tools. ```text validate=true ``` -------------------------------- ### Handle Push Notification Deep Links with Branch SDK Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Integrate Branch SDK to handle deep links received via push notifications. This allows users to be directed to specific content within the app upon tapping a notification. Requires specific payload structure on the server. ```objectivec #import // In your push notification handler - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Check if notification contains a Branch link NSString *branchLink = userInfo[@"branch"]; if (branchLink) { [[Branch getInstance] handlePushNotification:userInfo]; } completionHandler(UIBackgroundFetchResultNewData); } // When creating push notifications on your server, include: // { // "aps": { "alert": "Check out our new product!" }, // "branch": "https://example.app.link/product123" // } ``` -------------------------------- ### Register Deep Link Controllers with Branch SDK Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Register custom view controllers to automatically handle and display content based on deep link data. This enables a seamless user experience by routing users to the correct screen upon opening a deep link. ```objectivec #import #import // Create a view controller that conforms to BranchDeepLinkingController @interface ProductViewController : UIViewController @property (weak, nonatomic) id deepLinkingCompletionDelegate; @end @implementation ProductViewController - (void)configureControlWithData:(NSDictionary *)data { NSString *productId = data[@"product_id"]; NSString *productName = data[@"product_name"]; // Configure your view controller with the deep link data self.productIdLabel.text = productId; self.productNameLabel.text = productName; } - (IBAction)closeButtonTapped:(id)sender { // Notify Branch that deep link handling is complete [self.deepLinkingCompletionDelegate deepLinkingControllerCompletedFrom:self]; } @end // Register the controller in AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ProductViewController *productVC = [[ProductViewController alloc] init]; // Register with presentation option [[Branch getInstance] registerDeepLinkController:productVC forKey:@"product_id" withPresentation:BNCViewControllerOptionPresent]; // Initialize Branch with auto-display [[Branch getInstance] initSessionWithLaunchOptions:launchOptions automaticallyDisplayDeepLinkController:YES]; return YES; } ``` -------------------------------- ### Control Data Collection Levels with Branch SDK Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Configure data collection levels for privacy compliance (GDPR, CCPA). Options range from full data collection to minimal or none, affecting attribution and deep linking capabilities. Also includes DMA parameter settings for EEA compliance and handling App Tracking Transparency (ATT) status. ```objectivec #import // Set Consumer Protection Attribution Level // BranchAttributionLevelFull - All data (default) // BranchAttributionLevelReduced - Device IDs, local IP, data integrations // BranchAttributionLevelMinimal - Device IDs, local IP, deep linking // BranchAttributionLevelNone - Only deterministic deep linking // For full GDPR compliance when user opts out [[Branch getInstance] setConsumerProtectionAttributionLevel:BranchAttributionLevelNone]; // For reduced tracking [[Branch getInstance] setConsumerProtectionAttributionLevel:BranchAttributionLevelReduced]; // Set DMA parameters for EEA region compliance [Branch setDMAParamsForEEA:YES // User is in EEA AdPersonalizationConsent:NO // User denied ad personalization AdUserDataUsageConsent:NO]; // User denied data usage for ads // Handle App Tracking Transparency #import if (@available(iOS 14, *)) { [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) { [[Branch getInstance] handleATTAuthorizationStatus:status]; }]; } // URL filtering - prevent sensitive URLs from being tracked [[Branch getInstance] setUrlPatternsToIgnore:@[ @".*oauth.*", @".*login.*", @".*password.*" ]]; // Check tracking status if ([Branch trackingDisabled]) { NSLog(@"Branch tracking is disabled"); } ``` -------------------------------- ### Retrieve Last Attributed Touch Data (LATD) with Branch SDK (Objective-C) Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt This code retrieves the last attributed touch data, which is crucial for understanding user acquisition sources and campaign performance. It requires the Branch SDK and allows specifying an attribution window in days. The output includes various attribution details and custom data from the referring link. ```objectivec #import // Request LATD with 30-day attribution window [[Branch getInstance] lastAttributedTouchDataWithAttributionWindow:30 completion:^(BranchLastAttributedTouchData * _Nullable latd, NSError * _Nullable error) { if (latd) { NSLog(@"Attribution window: %@", latd.attributionWindow); NSLog(@"Attribution data: %@", latd.lastAttributedTouchJSON); // Access attribution details NSDictionary *data = latd.lastAttributedTouchJSON; NSString *campaign = data[@"~campaign"]; NSString *channel = data[@"~channel"]; NSString *feature = data[@"~feature"]; // Custom data from the link NSString *referrer = data[@"referrer_id"]; } else if (error) { NSLog(@"LATD error: %@", error); } }]; ``` -------------------------------- ### Opt-out of Facebook App Tracking (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This code demonstrates how to use the `limit_facebook_tracking` flag to allow developers to opt-out of Facebook app tracking. This functionality was added in version v0.21.16. It helps in managing user privacy preferences related to ad tracking. ```objective-c [[Branch getInstance] setLimitFacebookTracking:YES]; ``` -------------------------------- ### Objective-C: Control Branch SDK Session Tracking Source: https://context7.com/branchmetrics/ios-branch-sdk-spm/llms.txt Demonstrates how to disable and resume automatic session tracking in the Branch iOS SDK. This is useful for scenarios where the app might briefly go into the background, such as during biometric authentication. The SDK defaults to a 30-second timeout when disabling sessions. ```objectivec #import // Disable next foreground session (e.g., for Face ID prompt) // Default 30 second timeout [Branch disableNextForeground]; // Disable with custom timeout [Branch disableNextForegroundForTimeInterval:60.0]; // 60 seconds // Resume session tracking manually [Branch resumeSession]; // Example: Handling biometric authentication - (void)presentBiometricAuth { // Disable Branch session during auth (app goes to background briefly) [Branch disableNextForegroundForTimeInterval:30.0]; LAContext *context = [[LAContext alloc] init]; [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"Authenticate to continue" reply:^(BOOL success, NSError *error) { // Resume Branch session [Branch resumeSession]; if (success) { [self proceedToApp]; } }]; } ``` -------------------------------- ### Adding `rating` field to BranchUniversalObject (Objective-C) Source: https://github.com/branchmetrics/ios-branch-sdk-spm/blob/main/ChangeLog.md This snippet shows how to add a `rating` field to a `BranchUniversalObject` instance. This feature was introduced in version v0.22.5 of the SDK. The `BranchUniversalObject` is used to represent content that can be shared or linked to. ```objective-c BranchUniversalObject *universalObject = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"item/12345"]; universalObject.title = @"My Awesome Item"; universalObject.rating = @5.0; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.