首页 > 解决方案 > Xamarin Forms 中 Android 项目中的 Xamarin iOS 参考

问题描述

我使用 Xamarin 创建了一个跨平台应用程序。我需要在我的项目中调用iOS和Android平台的原生函数。这是代码:

private static Func<IDownloadFile, string> _downloadPath = new Func<IDownloadFile, string>(file =>
{
    if (Device.RuntimePlatform == Device.iOS)
    {
        string fileName = (new NSUrl(file.Url, false)).LastPathComponent;
        return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
    }
    else if (Device.RuntimePlatform == Device.Android)
    {
        string fileName = Android.Net.Uri.Parse(file.Url).Path.Split('/').Last();
        return Path.Combine(Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath, fileName);
    }

    return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "");
});

这是来自通知插件的代码https://github.com/thudugala/Plugin.LocalNotification

问题是当我使用该代码时,Mono.Android 和 Xamarin.iOS 引用被添加到我的共享项目中Dependencies/Assemblies,然后当我尝试在发布模式下运行应用程序时出现引用错误 - 我注意到在我的 Android 项目中在 bin/Release 中有 Xamarin.iOS 参考,但在 Android 项目中没有参考。当我从代码中删除该引用Dependencies/Assemblies并注释本机调用时,一切都会正确编译。我为此感到困惑。我上面的代码是正确的还是我需要以另一种方式调用本机函数?

标签: xamarin.formsxamarin.android

解决方案


使用 .net Standard 时,采用的方法是使用一个接口来定义您要公开的功能,然后在每个平台中实现。

在共享中:

public interface IMyInterface
{
    string GetUrlPath(string fileUrl);
}

iOS 实现:

public class MyClass : IMyInterface
{
    public string GetUrlPath(string fileUrl)
    {
       string fileName = (new NSUrl(file.Url, false)).LastPathComponent;
       return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);             
    }
}

安卓实现:

public class MyClass : IMyInterface
{
    public string GetUrlPath(string fileUrl)
    {
        string fileName = (new NSUrl(file.Url, false)).LastPathComponent;
        return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName);
    }
}

然后使用 Xamarin.FormsDependencyService或任何其他 IoC 容器,您可以将接口与正确的实现相匹配。

在您的共享代码中,您将使用接口并且选择的实现将是透明的。

这篇文章展示了一个非常完整的例子来说明如何做到这一点。


推荐阅读