xamarin.forms - 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
并注释本机调用时,一切都会正确编译。我为此感到困惑。我上面的代码是正确的还是我需要以另一种方式调用本机函数?
解决方案
使用 .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 容器,您可以将接口与正确的实现相匹配。
在您的共享代码中,您将使用接口并且选择的实现将是透明的。
这篇文章展示了一个非常完整的例子来说明如何做到这一点。
推荐阅读
- apache-spark - 获取所有崩溃的 Spark Yarn Job 日志
- c - 构建 make 文件 arm 微控制器
- python - 使用 Pandas 的 DateTimeIndex 上的值计数从每个月中选择前 5 个
- laravel - 覆盖 BackpackForLaravel 中的翻译
- unity3d - 从用户操作中检测游戏对象移除
- python - 将张量批次与稀疏矩阵相乘
- c++ - 在 C++ 中读取 bmp 文件
- python-3.x - PyImgui 与 Pyglet 双打键盘输入
- python - 如果元素具有十进制值,python中的max(array)不会返回正确的值
- c# - Xamarin Forms 显示数据网格