gpt4 book ai didi

c# - 如何从 ContentPage 获取应用版本?

转载 作者:太空狗 更新时间:2023-10-29 22:07:54 24 4
gpt4 key购买 nike

我试过这个:iPhone MonoTouch - Get Version of Bundle

NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion").ToString();

但这没有用。因为找不到 NSBundle

如何从 ContentPage 获取应用程序版本(iOS 和 Android)?

我最终得到的代码(感谢 Steven Thewissen):

PCL(共享代码)

using System;
namespace MyApp.Interfaces
{
public interface IApplicationVersion
{
string ApplicationsPublicVersion { get; set; }
string ApplicationsPrivateVersion { get; set; }
}
}

安卓

using System;
using MyApp.Droid.Helpers;
using MyApp.Interfaces;
using Xamarin.Forms;

[assembly: Dependency(typeof(ApplicationVersion))]
namespace MyApp.Droid.Helpers
{
public class ApplicationVersion : IApplicationVersion
{
public string ApplicationsPublicVersion { get; set; }
public string ApplicationsPrivateVersion { get; set; }

public ApplicationVersion()
{
var context = Android.App.Application.Context;
var info = context.PackageManager.GetPackageInfo(context.PackageName, 0);

ApplicationsPublicVersion = info.VersionName;
ApplicationsPrivateVersion = info.VersionCode.ToString();
}
}
}

iOS

using System;
using MyApp.Interfaces;
using MyApp.iOS.Helpers;
using Foundation;
using Xamarin.Forms;

[assembly: Dependency(typeof(ApplicationVersion))]
namespace MyApp.iOS.Helpers
{
public class ApplicationVersion : IApplicationVersion
{
public string ApplicationsPublicVersion { get; set; }
public string ApplicationsPrivateVersion { get; set; }

public ApplicationVersion()
{
ApplicationsPublicVersion = NSBundle.MainBundle.InfoDictionary[new NSString("CFBundleShortVersionString")].ToString();
ApplicationsPrivateVersion = NSBundle.MainBundle.InfoDictionary[new NSString("CFBundleVersion")].ToString();
}
}
}

最佳答案

您可以通过实现依赖服务来做到这一点。首先,您在共享代码中定义一个接口(interface):

namespace MyApp
{
public interface IAppVersionProvider
{
string AppVersion { get; }
}
}

然后在每个平台项目中实现接口(interface)。

iOS

[assembly: Dependency(typeof(AppVersionProvider))]
namespace MyApp.iOS
{
public class AppVersionProvider : IAppVersionProvider
{
public string AppVersion => NSBundle.MainBundle.InfoDictionary[new NSString("CFBundleVersion")].ToString();
}
}

安卓

[assembly: Dependency(typeof(AppVersionProvider))]
namespace MyApp.Droid
{
public class AppVersionProvider : IAppVersionProvider
{
public string AppVersion
{
get
{
var context = Android.App.Application.Context;
var info = context.PackageManager.GetPackageInfo(context.PackageName, 0);

return $"{info.VersionName}.{info.VersionCode.ToString()}";
}
}
}
}

然后您可以通过以下方式从共享代码中检索版本号:

var version = DependencyService.Get<IAppVersionProvider>();
var versionString = version.AppVersion;

关于c# - 如何从 ContentPage 获取应用版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com