Branch - cleveradssolutions/CAS-Track-revenue GitHub Wiki

Integrate the SDK into your app


The integration of Branch SDK into your application is presented in the official source.

Track CAS revenue

Initialization

Android

More information about initialization of CAS SDK here and Branch SDK here.

  • Add Branch to your CustomApplicationClass.java
public class GlobalApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        
        // Initialize CAS
        CAS.buildManager().initialize(); 

        // Branch object initialization
        Branch.getAutoInstance(this);
    }
}
  • Add Branch to your LauncherActivity.java
public class LauncherActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
    }

    @Override public void onStart() {
        super.onStart();
        Branch.sessionBuilder(this).withCallback(branchReferralInitListener).withData(getIntent() != null ? getIntent().getData() : null).init();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // if activity is in foreground (or in backstack but partially visible) launching the same
        // activity will skip onStart, handle this case with reInitSession
        if (intent != null &&
              intent.hasExtra("branch_force_new_session") && 
              intent.getBooleanExtra("branch_force_new_session")) {
            Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
        }
    }

    private Branch.BranchReferralInitListener branchReferralInitListener = new Branch.BranchReferralInitListener() {
        @Override
        public void onInitFinished(JSONObject linkProperties, BranchError error) {
            // do stuff with deep link data (nav to page, display content, etc)
        }
    };
iOS

More information about initialization of CAS SDK here and Branch SDK here.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
{
    // Initialize CAS
    let manager = CAS.create(managerID: "demo",
                             enableTypes: [.banner, .interstitial, .rewarded],
                             demoAdMode: true) { complete, error in
               print("[CAS Sample] Mediation manager initialization: \(complete) with error: \(String(describing: error))")
           }

    // Configure Branch SDK
    // if you are using the TEST key
    Branch.setUseTestBranchKey(true)

    // listener for Branch Deep Link data
    Branch.getInstance().initSession(launchOptions: launchOptions) { (params, error) in
    
    return true;
  }
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return Branch.getInstance().application(app, open: url, options: options)
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    // handler for Universal Links
    return Branch.getInstance().continue(userActivity)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // handler for Push Notifications
    Branch.getInstance().handlePushNotification(userInfo)
}
Unity3d

More information about initialization of CAS SDK here and Branch SDK here.

Configure App

Initialize CAS SDK

class CleverAdsSolutionsDemoScript : MonoBehaviour
{
    IMediationManager manager;
    void Start()
    {
        // Initialize CAS
        manager = builder.Initialize();
    }
}

Initialize Branch SDK

Add the Branch prefab asset to the first scene of your Unity project

Do not forget to click on the Update iOS Wrapper and the Update Android Manifest buttons once you are done.

  • Simulate Fresh Installs - This checkbox enables debug mode. This allows you to simulate fresh every time you uninstall and reinstall the app. Please make sure to uncheck this box before releasing your app.

  • Test Mode - This checkbox picks the test key from your Branch prefab. If this box is unchecked, by default, your live Branch key is used.

  • Test Branch Key - This is the test Branch key found on the App Settings page of your Test Branch app.

  • Test Branch URI - This is the test URI scheme that you have set for your app on the Link Settings page for your Test Branch app.

  • Test Android Path Prefix - This field is only applicable if you are on the bnc.lt domain of your Test Branch app. You can find it underneath the field labeled SHA256 Cert Fingerprints on the Link Settings page once you’ve enabled App Links. It will look something like this: /WSuf (the initial / character should be included).

  • Test App Links - This field is applicable if you want to enable APPLINKS and UNIVERSAL LINKS for your domain. Please make sure to add the correct domain found on the bottom of the Link Settings page of your Test Branch app. Add the -alternate domain to have your Branch links deeplink from your Deepviews and Journeys. If you are not using a app.links domain please contact Branch support team.

  • Live Branch Key - This is the Live Branch key found on the App Settings page of your Live Branch app.

  • Live Branch URI - This is the Live URI scheme that you have set for your app on the Link Settings page for your Live Branch app.

  • Live Android Path Prefix - This field is only applicable if you are on the bnc.lt domain of your Live Branch app. You can find it underneath the field labeled SHA256 Cert Fingerprints on the Link Settings page once you’ve enabled App Links. It will look something like this: /WSuf (the initial / character should be included).

  • Live App Links - This field is applicable if you want to enable APPLINKS and UNIVERSAL LINKS for your domain. Please make sure to add the correct domain found on the bottom of the Link Settings page of your Live Branch app. Add the -alternate domain to have your Branch links deeplink from your Deepviews and Journeys. If you are not using a app.links domain please contact Branch support team.

Initialize Branch SDK

class CleverAdsSolutionsDemoScript : MonoBehaviour
{
    IMediationManager manager;
    void Awake() 
    {
        DontDestroyOnLoad(this);
    }   
 
    void Start()
    {
        // Initialize CAS
        manager = builder.Initialize();
  
        // Initialize Branch SDK 
        Branch.initSession(CallbackWithBranchUniversalObject);
    }

    void CallbackWithBranchUniversalObject(BranchUniversalObject buo,
                                              BranchLinkProperties linkProps,
                                                string error) {
        if (error != null) {
            System.Console.WriteLine("Error : "
                                    + error);
        } else if (linkProps.controlParams.Count > 0) {
            System.Console.WriteLine("Deeplink params : "
                                    + buo.ToJsonString()
                                    + linkProps.ToJsonString());
        }
    }
}

Track Impression Level Data

Android

Use our Ad Content Callback for tracking your Impression Level Data.

class MyActivity implements AdCallback {
  MediationManager manager; 
  CASBannerView banner;

  void createBanner() {
      banner = new CASBannerView(this, manager);
      banner.setListener(this);
  }

  void showInterstitial() {
      manager.showInterstitial(MyActivity.this, this);
  }

  void showRewarded() {
      manager.showRewarded(MyActivity.this, this);
  }

  @Override
  void onShown(AdStatusHandler ad) {
     // Executed when the ad is begin displayed.
     // AdStatusHandler is information of ad impression.

     BranchEvent event = new BranchEvent(BRANCH_STANDARD_EVENT.VIEW_AD)
             .setCurrency(CurrencyType.USD)
             .addCustomDataProperty("Network", adStatusHandler.getNetwork());

     switch (adStatusHandler.getAdType()) {
         case Banner:
             event.setAdType(io.branch.referral.util.AdType.BANNER);
             break;
         case Interstitial:
             event.setAdType(io.branch.referral.util.AdType.INTERSTITIAL);
             break;
         case Rewarded:
             event.setAdType(io.branch.referral.util.AdType.REWARDED_VIDEO);
             break;
         default:
             break;
     }

     if (adStatusHandler.getPriceAccuracy() != PriceAccuracy.UNDISCLOSED) {
         event.setRevenue(adStatusHandler.getCpm() / 1000);
         event.addCustomDataProperty("PriceAccuracy",
                 adStatusHandler.getPriceAccuracy() == PriceAccuracy.BID ? "BID" : "FLOOR");
     } else {
         event.addCustomDataProperty("PriceAccuracy", "UNDISCLOSED");
     }

     event.logEvent(this);  
}
iOS

Use our Ad Content Callback for tracking your Impression Level Data.

class AdExample : UIViewController, CASCallback {
    let manager: CASMediationManager
    @IBOutlet var bannerView: CASBannerView!
    
    func createBanner() {
        bannerView.rootViewController = self
        bannerView.delegate = self
    }
    
    func showInterstitial() {
        manager.presentInterstitial(fromRootViewController: self, callback: self)
    }
    
    func showRewarded() {
        manager.presentRewardedAd(fromRootViewController: self, callback: self)
    }

    func willShown(ad adStatus: CASStatusHandler) {
        let event = BranchEvent.standardEvent(.viewAd)
        event.currency = .USD
        
        var params : [String : String] = ["AdType" : adStatus.adType.description, "Network" : adStatus.network]
        
        switch adStatus.adType {
            case .banner:
                event.adType = .banner
                break
            case .interstitial:
                event.adType = .interstitial
                break
            case .rewarded:
                event.adType = .rewardedVideo
                break
            default:
                break
        }
        
        if (adStatus.priceAccuracy != CASPriceAccuracy.undisclosed) {
            let cpm = NSDecimalNumber.init(value: adStatus.cpm / 1000)
            event.revenue = cpm
            
            if (adStatus.priceAccuracy == CASPriceAccuracy.bid) {
                params["PriceAccuracy"] = "BID"
            } else {
                params["PriceAccuracy"] = "FLOOR"
            }
        } else {
            params["PriceAccuracy"] = "UNDISCLOSED"
        }
        
        event.customData = params
        
        event.logEvent()
    }
}
Unity3d

Use our Ad Content Callback for tracking your Impression Level Data.

class CleverAdsSolutionsDemoScript : MonoBehaviour
{
    IMediationManager manager;
    
    void Start()  
    {
        manager.OnBannerAdOpening += onAdOpening;
        manager.OnInterstitialAdOpening += onAdOpening;
        manager.OnRewardedAdOpening += onAdOpening;
    }

    void showInterstitial()
    {
        manager.ShowAd( AdType.Interstitial );
    }

    void showRewarded()
    {
        manager.ShowAd( AdType.Rewarded );
    } 

    void showBanner()
    {
        manager.ShowAd( AdType.Banner );
    }
     
    void onAdOpening(AdMetaData adMetaData)
    {
        // Executed when the ad is begin displayed.
        // AdStatusHandler is information of ad impression.
        
        BranchEvent branchEvent = new BranchEvent( BranchEventType.VIEW_AD );

        branchEvent.SetCurrency( BranchCurrencyType.USD );
        branchEvent.AddCustomData( "Network", adMetaData.network.ToString() );
        branchEvent.AddCustomData( "AdType", adMetaData.type.ToString() );

        if ( adMetaData.priceAccuracy != PriceAccuracy.Undisclosed )
            branchEvent.SetRevenue( (float)adMetaData.cpm / 1000.0f );

        branchEvent.AddCustomData( "PriceAccuracy", adMetaData.priceAccuracy.ToString() );
        Branch.sendEvent(branchEvent);
    }
}
⚠️ **GitHub.com Fallback** ⚠️