You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中无法找到iOSBackgroundService类型或命名空间问题求助

问题:未能找到类型或命名空间名称“iOSBackgroundService”

我在Platform -> iOS目录下创建了iOSBackgroundService类,但在MAUI程序中无论是依赖注入还是直接实例化都报错“未能找到类型或命名空间名称‘iOSBackgroundService’”。同一目录下的默认AppDelegate类却能正常使用,完全找不到问题所在。

依赖注入代码报错示例:

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

直接实例化报错示例:

var iOSBck = new iOSBackgroundService();

参考代码

MauiProgram.cs完整代码

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();
        }
    }
}

iOSBackgroundService.cs代码

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;
            }
        }
    }
}

IBackgroundService接口代码

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();
    }
}

解决方法

问题出在命名空间引用错误:

你的iOSBackgroundService类所在的命名空间是HR_Attendance_MAUI.Platforms.iOS.Services,但在MauiProgram.cs中,iOS条件编译块里的using语句只引用了HR_Attendance_MAUI.Platforms.iOS,没有包含Services子命名空间,导致编译器找不到该类。

修正步骤:

  1. 打开MauiProgram.cs
  2. 将iOS条件编译块中的using语句修改为:
#elif IOS
using HR_Attendance_MAUI.Platforms.iOS.Services; 
#endif
  1. 重新编译项目即可解决报错。

另外,检查一下iOSBackgroundService类的文件是否放在正确的目录(Platforms/iOS/Services)下,MAUI的平台特定代码需要放在对应平台目录中才能被正确识别。

内容的提问来源于stack exchange,提问作者Galaxylokka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 01:32:04