[iOS] Swift Analytic Best Practise

Image for post
Image for post

In this article, We are going to implement Analytics class for Google Ads. The idea was to track the ads that display in the app.

We have two types of ads in the app.

  1. Interstitial ads are full-screen ads that cover the interface of their host app. They’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

For the best practice, we have implemented separate enums. One for the events and second for the type of events. Following enum adEvent we have added two events as well one method inside the enum which will return the events string.

For instance, if we use the following code

adEvent.getName(.viewAdBanner)()

It will return you String “view_ad_banner”

The second enum we are using the adType

Finally, AdAnalyticsModel Class which use above enum adType with the method trackAd

You can track your ads as following

let adAnalyticsModel = AdAnalyticsModel()adAnalyticsModel.trackAd(typeOfAd: .banner, adUnitId: "123")adAnalyticsModel.trackAd(typeOfAd: .interstitial, adUnitId: "456")

will Print

Output:adUnitId  123
adType view_ad_banner
adUnitId 456
adType view_ad_int

We can replace the print() with any analytic code i.e Firebase etc.

You can try to run the full program below to see the results.

Thank you for the reading :)

Written by

We teach & develop for startups

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store