home | Parental Gate for Kids' apps in Xamarin

4/26/2020 9:37:18 PM

#programming #xamarin #xamarin.forms #xamarin.ios #appstore

hero image

A few days ago, a friend asked me to help with an app she built for children. The app is fairly simple and, as you might have already guessed, ad-supported. The problem was Apple requirement for a "Parental Gate".

In simple words, when the user taps on an ad banner, they should be asked to complete a simple task for an adult and yet hard for a child to get "confirmation".

The solution that we came up with, implemented, and got the app on the AppStore is kinda simple so without further ado, let's see some code.

In a View:

            <local:AdControlView
                Grid.Row="2"
                Grid.ColumnSpan="2"
                AdUnitId="{Binding AdId}"
                BackgroundColor="White"
                HorizontalOptions="EndAndExpand" />
            <Grid
                Grid.Row="2"
                Grid.ColumnSpan="2"
                HeightRequest="50"
                BackgroundColor="Transparent"
                IsVisible="{Binding GuardAd}">
                <Grid.GestureRecognizers>
                    <TapGestureRecognizer
                        Command="{Binding AdGridTapCommand}" />
                </Grid.GestureRecognizers>
            </Grid>

Which is a simple XAML. A custom banner control and a grid (could be StackLayout or any other control) that overlays it. When the view is presented, the ad is loaded and "above" it a grid that is transparent so the ad content is visible but doesn't receive touch yet.

In a ViewModel we have:

        Random random;
				
        bool guardAd;
        public bool GuardAd
        {
            get => guardAd;
            set => SetProperty(ref guardAd, value);
        }

random to generate numbers and GuardAd is whether the banner is "guarded" or not, that is if the overlay is "visible" or not.

The method that is fired when the grid overlay is tapped is shown below, we simply generate two random integers and ask the user to answer with their sum.

If the result is correct, then hide the overlay for three seconds and that's it

        async void AdGridTap()
        {
            int firstNumber = random.Next(15, 45);
            int secondNumber = random.Next(15, 45);
            int sum = firstNumber + secondNumber;
            var res = await Dialogs.PromptAsync($"{firstNumber} + {secondNumber}", "answer below");
            GuardAd = !(res.Ok && int.TryParse(res.Text, out int userSum) && userSum == sum);
            Task.Run(GuardAdAgain);
        }

        async Task GuardAdAgain()
        {
            await Task.Delay(3000);
            MainThread.BeginInvokeOnMainThread(() => GuardAd = true);
        }

Hope you find it useful