Search code examples
ios.netdependency-injectionreferencemaui

The type or namespace name 'iOSBackgroundService' could not be found


Error Message : The type or namespace name 'iOSBackgroundService' could not be found

I have created new class named iOSBackgroundService in Platform -> iOS. But I cannot inject it in the maui program.

#elif IOS
            builder.Services.AddSingleton<IBackgroundService, iOSBackgroundService>();
#endif

And I cannot create object like this that leads to same message.

var iOSBck = new iOSBackgroundService();

But When I create object (or inject) of the default AppDelegate class that placed in the same directory (Platform->iOS). That doesn't show any error.

Actually I haven't any idea of it. Any help is appreciated.

This is full code of the mauiprogram.cs for your reference.

**using Microsoft.Extensions.Logging;
using Plugin.Fingerprint.Abstractions;
using Plugin.Fingerprint;
using Plugin.Maui.Biometric;
using HR_Attendance_MAUI.Services;

#if ANDROID
using HR_Attendance_MAUI.Platforms.Android.Services;
#elif IOS
using HR_Attendance_MAUI.Platforms.iOS; 
#endif


namespace HR_Attendance_MAUI
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });
            builder.Services.AddSingleton<MainPage>();
            builder.Services.AddSingleton<FinPrintReg_Page>();
            builder.Services.AddSingleton(typeof(IFingerprint), CrossFingerprint.Current);

#if DEBUG
            builder.Logging.AddDebug();
#endif
#if ANDROID
        builder.Services.AddSingleton<IBackgroundService, AndroidBackgroundService>();
#elif IOS
            builder.Services.AddSingleton<IBackgroundService, iOSBackgroundService>();
#endif

            return builder.Build();
        }
    }


}**

And this is the code of iOSBackgroundService

using Foundation;
using UIKit;
using HR_Attendance_MAUI.Services;
using HR_Attendance_MAUI.Data;
using HR_Attendance_MAUI.Model;
using System.Threading.Tasks;
using System.Collections.Generic;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.IO;
using Microsoft.Maui.Controls;
using HR_Attendance_MAUI.Platforms.iOS.Services;

[assembly: Dependency(typeof(iOSBackgroundService))]

namespace HR_Attendance_MAUI.Platforms.iOS.Services
{
    [Register("iOSBackgroundService")]
    public class iOSBackgroundService : NSObject, IBackgroundService
    {
        private nint _taskId;
        private Timer _timer;
        private AttendanceDatabaseService2 _attendanceDatabaseService;
        private readonly TimeSpan _delay = TimeSpan.FromMinutes(5);

        public static bool IsForegroundServiceRunning;

        public void Start()
        {
            IsForegroundServiceRunning = true;
            _taskId = UIApplication.SharedApplication.BeginBackgroundTask("BackgroundService", OnExpiration);

            Task.Run(async () =>
            {
                while (IsForegroundServiceRunning)
                {
                    var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AttendanceDB.db3");
                    _attendanceDatabaseService = new AttendanceDatabaseService2(dbPath);
                    List<AttendanceData> attendanceDataList = _attendanceDatabaseService.GetAllAttendances();

                    if (attendanceDataList.Count == 0)
                    {
                        Stop();
                    }

                    var networkAccess = Connectivity.NetworkAccess;
                    if (networkAccess == NetworkAccess.Internet)
                    {
                        bool result = await SyncAttendanceData();
                    }

                    Console.WriteLine("Background Service is Running");
                    await Task.Delay(_delay);
                }

                UIApplication.SharedApplication.EndBackgroundTask(_taskId);
                _taskId = UIApplication.BackgroundTaskInvalid;
            });
        }

        public void Stop()
        {
            IsForegroundServiceRunning = false;
            UIApplication.SharedApplication.EndBackgroundTask(_taskId);
        }

        public bool IsForeGroundServiceRunning()
        {
            return IsForegroundServiceRunning;
        }
        private void OnExpiration()
        {
            Stop();
        }

        private async Task<bool> SyncAttendanceData()
        {
            var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AttendanceDB.db3");
            _attendanceDatabaseService = new AttendanceDatabaseService2(dbPath);
            List<AttendanceData> attendanceDataList = _attendanceDatabaseService.GetAllAttendances();

            if (attendanceDataList.Count == 0)
            {
                return false;
            }

            foreach (AttendanceData attendanceData in attendanceDataList)
            {
                string inTimeDate = attendanceData.inTimeDate;
                string inTimeDate1 = attendanceData.outTime;
                string inTimeDate2 = attendanceData.lonOut;
                string inTimeDate3 = attendanceData.latOut;
            }

            DateTimeOffset currentTime1 = DateTimeOffset.Now;
            DateTime currentTime = currentTime1.DateTime;
            currentTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 0, 0, 0);
            string currentDate = currentTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

            HttpClient client;
            try
            {
                client = HttpClientFactory.CreateHttpClient();
                var response = await client.PostAsJsonAsync("api/Attendance/StoreList", attendanceDataList);

                if (response.IsSuccessStatusCode)
                {
                    _attendanceDatabaseService.StoreTodaysRecordsAndDeleteAll(currentDate);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                await App.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
                return false;
            }
        }
    }
}

Here is the IBackgroundService interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HR_Attendance_MAUI.Services
{
    public interface IBackgroundService
    {
        void Start();
        void Stop();

        bool IsForeGroundServiceRunning();
    }
}

Solution

  • Error Message : The type or namespace name 'iOSBackgroundService' could not be found

    According to the error log, you can fix it by changing the class name from HR_Attendance_MAUI.Platforms.iOS.Services to HR_Attendance_MAUI.Platforms.iOS under Platform -> iOS.