Flight by RockFrenzy

Dynamically Change the iOS App Icon in Xamarin.Forms

Tuğçe

--

In iOS 10.3, Apple added a function that allows us to dynamically change the icon of our application. The Apple documentation states that:

  • supportsAlternateIcons — It is readonly. A Boolean value indicating whether the app is allowed to change its icon. To make it True we need to set up alternative icons in info.plist.
  • ApplicationIconBadgeNumber -The number currently set as the badge of the app icon in Springboard.
  • alternateIconName — It is readonly. The name of the icon being displayed for the app.
  • setAlternateIconName — Changes the app’s icon. If we assign the icon name to null, our application uses the primary icon.

For more information, you can review Apple’s API documentation.

There are a few steps we need to follow to change the icon in our Xamarin.Forms application.

1. We must set up alternative icons that we will use in Info.plist.

We do not define these icons in Assets, as we always do. We put them in the Resources folder.

Info.plist:

2. We need to define the Dependency Service. For this purpose we define the IChanceIconService interface in our Portable project:

public interface IChangeIconService
{
void ChangeIcon(string iconName);
}

In iOS project:

SetAlternateIcon method here is a method that comes from the UIApplication class. Because the UIApplication class is designed according to the Singleton pattern, only one copy of it can be used through an application lifecycle. If we try to derive it these exception will be throw:

NSInternalInconsistencyException: There can only be one UIApplication instance

As stated in Xamarin Documentation

Application developers may subclass UIApplication and use the principalClassName argument to the UIApplication.Main(string[],string,string) method to specify their subclass. In that situation, developers must create a public constructor for their subclass that the runtime will call appropriately.

If we want to create and use a custom UIApplication, we need to create a class that inherits from UIApplication class and define it in the Main class.

UIApplication.SharedApplication

returns the current UIApplication object. We can then use this to access the SetAlternateIcon method and modify our application’s icon.

You can download full GitHub project in here.

--

--

No responses yet