iOS .NET MAUI 中的 DependencyService 问题:无法获取 IFileHelper 的实例,始终返回 null

问题描述 投票:0回答:1

我正在开发一个 .NET MAUI 应用程序,该应用程序使用 DependencyService 来获取 iOS 上文件的本地路径。尽管我已按照说明正确注册了 IFileHelper 实现,但我总是收到异常,指出无法获取 IFileHelper 实例。 共享项目中的代码

IFileHelper.cs:

namespace App7.Clases.BasesDatos 
{     
public interface IFileHelper     
{        
string GetLocalFilePath(string filename);     
} 
}

代码直接跳转到catch块,并没有获取文件路径

ResultadosBD.cs:

using System;
using System.IO;
using Microsoft.Maui.Controls;

namespace App7.Clases.BasesDatos
{
    public partial class ResultadosBD : ContentPage
    {
        private readonly DatosRepository? _datosRepository;

        public ResultadosBD()
        {
            InitializeComponent(); 
            try
            {
                var fileHelper = DependencyService.Get<IFileHelper>();
                if (fileHelper == null)
                {
                    throw new Exception("No se pudo obtener una instancia de IFileHelper.");
                }

                string databasePath = fileHelper.GetLocalFilePath("OMSAnthroP.db3");

                 if (File.Exists(databasePath))
                {
                    Console.WriteLine($"El archivo de base de datos existe en la ruta: {databasePath}");
                }
                else
                {
                    Console.WriteLine($"El archivo de base de datos no existe en la ruta: {databasePath}");
                     CreateDatabaseFile(databasePath);
                    Console.WriteLine($"Archivo de base de datos creado en la ruta: {databasePath}");
                }

                try
                {
                    // Inicializar el repositorio de datos
                    _datosRepository = new DatosRepository(databasePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error al inicializar el repositorio de datos: {ex.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error al obtener la ruta del archivo: {ex.Message}");
            }
        }

        private void CreateDatabaseFile(string path)
        {
            // Implementa la lógica para crear el archivo de base de datos aquí
        }
    }
}

FileHelper.cs:

using System;
using System.IO;
using Foundation;
using App7.Clases.BasesDatos;
using Microsoft.Maui.Controls;

[assembly: Dependency(typeof(App7.iOS.FileHelper))]
namespace App7.iOS
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            string downloadPath;

            NSFileManager fileManager = NSFileManager.DefaultManager;
            NSUrl[] urls = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);
            if (urls != null && urls.Length > 0 && urls[0] != null)
            {
                downloadPath = urls[0].Path ?? throw new Exception("El Path de la URL es nulo.");
            }
            else
            {
                throw new Exception("No se pudo obtener el directorio de documentos de la aplicación.");
            }

            return Path.Combine(downloadPath, filename);
        }
    }
}

什么可能导致

DependencyService.Get<IFileHelper>()
在我的 .NET MAUI for iOS 应用程序中始终返回 null?

预先感谢您提供的任何帮助。

visual-studio visual-studio-code maui maui-community-toolkit
1个回答
0
投票

在MAUI中,如果要调用平台代码,可以使用条件编译部分类和方法

这是一个使用部分类和方法的演示。

1.创建一个Partial跨平台类,命名为FileHelperService

public partial class FileHelperService
{
    public partial string GetLocalFilePath(string filename);
}

2.在Platform/iOS文件夹中,同时创建一个名为FileHelperService的分部类来实现iOS平台上的API。

public partial class FileHelperService
{
    public string GetLocalFilePath(string filename)
    {
        string downloadPath;

        NSFileManager fileManager = NSFileManager.DefaultManager;
        NSUrl[] urls = fileManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);
        if (urls != null && urls.Length > 0 && urls[0] != null)
        {
            downloadPath = urls[0].Path ?? throw new Exception("El Path de la URL es nulo.");
        }
        else
        {
            throw new Exception("No se pudo obtener el directorio de documentos de la aplicación.");
        }

        return Path.Combine(downloadPath, filename);
    }
}

3.如果你想调用FileHelperService,就这样吧,

    try
    {
        var fileHelper = new FileHelperService();
        string filePath = fileHelper.GetLocalFilePath(filename);
        ...        

    }
© www.soinside.com 2019 - 2024. All rights reserved.