Background Tasks in iOS ?

ArselanArselan Member ✭✭
edited September 17 in Xamarin.iOS

Hi everyone,
Today I need to implement notifications service in my xamarin forms app..
The idea is that I must have a service that works in the background (even when the app is not launched) so the role of this service is to check if there are a new informations (using web api and JSON).. if so, a local notification will be sent to the user...
I've actually completed this work on the android platform using Android Services && Alarm Manager.. it works fine but I really have no idea how to do the same work on the iOS platform!
You can check my code here.

From here we start/stop the android service (from shared project)

private void NotificationsSwitch_Toggled(object sender, ToggledEventArgs e) { if (NotificationsSwitch.IsToggled) { if (Device.RuntimePlatform == Device.Android && IsNotificationsEnabled.Equals(false)) { DependencyService.Get<IAndroidNotifications>().StartNotificationsService(); } } else { if (Device.RuntimePlatform == Device.Android) { DependencyService.Get<IAndroidNotifications>().StopNotificationsService(); } } }

Notifications class | Android Project

`[assembly: Dependency(typeof(Notifications))]
namespace MyApp.Droid
{
class Notifications : Activity, IAndroidNotifications
{
Context context = Android.App.Application.Context;

    public void StartNotificationsService()
    {
        //Start Notifications Service
        Intent myIntent = new Intent(context, typeof(NotificationsService));
        context.StartService(myIntent);


        //Show Snackbar message
        Activity activity = CrossCurrentActivity.Current.Activity;
        Android.Views.View activityRootView = activity.FindViewById(Android.Resource.Id.Content);
        Snackbar.Make(activityRootView, "Notifications on", Snackbar.LengthLong).Show();
    }

    public void StopNotificationsService()
    {
        //Stop Notifications Service
        Intent myIntent = new Intent(context, typeof(NotificationsService));
        context.StopService(myIntent);


        //Show Snackbar message
        Activity activity = CrossCurrentActivity.Current.Activity;
        Android.Views.View activityRootView = activity.FindViewById(Android.Resource.Id.Content);
        Snackbar.Make(activityRootView, "Notifications off", Snackbar.LengthLong).Show();
    }

    public bool CheckNotificationsService()
    {
        ActivityManager manager = (ActivityManager)context.GetSystemService(Context.ActivityService);
        foreach (var service in manager.GetRunningServices(int.MaxValue))
        {
            string x = service.Service.ClassName;
            if (service.Service.ClassName == "com.TestApp.NotificationsService") 
            {
                return true;
            }
        }
        return false;
    }

    private void StartAlarm(bool isRepeating)
    {
        AlarmManager manager = (AlarmManager)GetSystemService(Context.AlarmService);
        Intent myIntent;
        PendingIntent pendingIntent;


        myIntent = new Intent(this, typeof(NotificationsAlarm));
        pendingIntent = PendingIntent.GetBroadcast(this, 0, myIntent, 0);


        if (!isRepeating)
        {
            manager.Set(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime() + 3000, pendingIntent);
        }
        else
        {
            manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime() + 3000, 60 * 1000, pendingIntent);
        }

    }
}

}`

Notifications Service | Android Project

`[Service
(Name = "com.TestApp.NotificationsService",
Label = "Service Notifications")]
class NotificationsService : Service
{
AlarmManager manager;
Intent myIntent;
PendingIntent pendingIntent;

    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    //[return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        //return base.OnStartCommand(intent, flags, startId);
        manager = (AlarmManager)GetSystemService(Context.AlarmService);



        myIntent = new Intent(this, typeof(NotificationsAlarm));
        pendingIntent = PendingIntent.GetBroadcast(this, 0, myIntent, 0);

        manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime() + 1000, 60 * 1000, pendingIntent);


        //Toast.MakeText(this, "Greating from our first service", ToastLength.Long).Show();
        return StartCommandResult.Sticky;
    }

    public override void OnDestroy()
    {
        base.OnDestroy();
        pendingIntent.Cancel();
        manager.Cancel(pendingIntent);
    }

}

}`

Broadcast receiver | Android Project

`namespace TestApp.Droid
{
[BroadcastReceiver(Enabled = true)]
public class NotificationsAlarm : BroadcastReceiver
{
static Random random = new Random();
int randomNumber = random.Next(0, 1000);

    InfosAPI _infosAPI;
    public override void OnReceive(Context context, Intent intent)
    {
        Toast.MakeText(context, "Received intent!", ToastLength.Long).Show();
        //CrossLocalNotifications.Current.Show("title "+ randomNumber, "notification body here\nthanks :D", randomNumber);

        testAPI(context, intent);
    }

    async void testAPI(Context context, Intent intent)
    {
        if (Connectivity.NetworkAccess == NetworkAccess.Internet)
        {
            InfosDO infos = new InfosDO();
            _infosAPI = new InfosAPI();

            var infosContent = await _infosAPI.GetInfosByID(new Guid(ConnectedUser.ID), "", "", new Guid(ConnectedUser.TiersID));
            BaseApiResponse apiInfosResponse = JsonConvert.DeserializeObject<BaseApiResponse>(infosContent);

            if (apiInfosResponse != null && !apiInfosResponse .IsError && apiInfosResponse .ResponseBusinessObject != null)
            {
                infos = JsonConvert.DeserializeObject<InfosDO>(apiInfosResponse .ResponseBusinessObject.ToString());

                // Build the notification:
                var builder = new NotificationCompat.Builder(context)
                      .SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
                              .SetContentTitle(infos.Title) // Set the title
                              .SetNumber(1) // Display the count in the Content Info
                              .SetSmallIcon(Resource.Drawable.ic_action_date_range) // This is the icon to display
                              .SetContentText(infos.Content); // the message to display.

                builder.SetDefaults(-1);

                // Finally, publish the notification:
                var notificationManager = NotificationManagerCompat.From(context);
                notificationManager.Notify(randomNumber, builder.Build());
            }
            else
            {
            }
        }
        else
        {
        }
    }
}

}`

I have no experience with iOS, can someone help me to implement this same work on iOS platform ?
thanks in advance :smile:

Sign In or Register to comment.