如何查看.net maui的最新版本?

eit6fx6z  于 2023-07-01  发布在  .NET
关注(0)|答案(2)|浏览(125)

我是.NET Maui的新手。我想通知拥有我的应用程序旧版本的用户,商店中有新版本可用。当用户单击Login按钮时,我使用以下几行代码成功地做到了这一点:

[RelayCommand]

async Task Login()
{

    var isLatest = await CrossLatestVersion.Current.IsUsingLatestVersion();

    if (!isLatest)
    {
        await Application.Current.MainPage.DisplayAlert("Update", 
              "New version available", "OK");
        await CrossLatestVersion.Current.OpenAppInStore();
    }
    else
    {...}
}

但我想在登录页面出现之前通知用户。我试着在方法中做

  • protected override async void OnAppearing()*

但它不工作,似乎调用

  • CrossLatestVersion.Current.IsUsingLatestVersion();*

死了,没有任何错误,也没有任何回应
有什么建议吗?提前感谢大家!!

ffdz8vbo

ffdz8vbo1#

参考上面的评论,这里是我用来从商店获得最新版本的应用程序的代码片段。这与您正在使用的nugget包中使用的技术相同。尝试进入你使用的金块的GitHub,它类似。

public async Task<string> GetLatestVersionAvailableOnStores()
        {
            string remoteVersion = "";
            string bundleID = YOUR_BUNDLE_ID;
            bool IsAndroid = DeviceInfo.Current.Platform == DevicePlatform.Android;

            var url = IsAndroid ?
                "https://play.google.com/store/apps/details?id=" + bundleID :
                "http://itunes.apple.com/lookup?bundleId=" + bundleID;

            using (HttpClient httpClient = new HttpClient())
            {
                string raw = await httpClient.GetStringAsync(new Uri(url));

                if (IsAndroid)
                {
                    var versionMatch = Regex.Match(raw, @"\[\[""\d+.\d+.\d+""\]\]"); //look for pattern [["X.Y.Z"]]
                    if (versionMatch.Groups.Count == 1)
                    {
                        var versionMatchGroup = versionMatch.Groups[0];
                        if (versionMatchGroup.Success)
                            remoteVersion = versionMatch.Value.Replace("[", "").Replace("]", "").Replace("\"", "");
                    }
                }
                else
                {
                    JObject obj = JObject.Parse(raw);
                    if (obj != null)
                        remoteVersion = obj["results"]?[0]?["version"]?.ToString() ?? "9.9.9";
                }
            }

            return remoteVersion;
        }

您可以通过在项目中使用任何静态变量来获得应用程序版本。然后你可以在两个字符串之间执行比较。我使用自然比较来检查哪个是最新版本。

iOS:

            SharedProjectClass.ApplicationVersion = NSBundle.MainBundle.InfoDictionary["CFBundlePublicVersionString"].ToString();

Android:

            SharedPRojectClass.ApplicationVersion = PackageManager.GetPackageInfo(PackageName, 0).VersionName;

Common Project:
    public static class SharedProjectCLass
    {
        /// <summary>
        /// The application version.
        /// </summary>
        public static string ApplicationVersion;
     }
async Task CheckVersion()
{
            var currentVersion = SharedProjectClass.ApplicationBuildNumber;

            var remoteVersion = await GetLatestVersionAvailableOnStores();

            // Function to natural compare the App version of format d.d.d
            Func<string, string, bool> CompareNaturalStringsOfAppVersion = (currentVersion, remoteVersion) =>
            {
                string[] components1 = currentVersion.Split('.');
                string[] components2 = remoteVersion.Split('.');

                for (int i = 0; i < components1.Length; i++)
                {
                    int value1 = Convert.ToInt32(components1[i]);
                    int value2 = Convert.ToInt32(components2[i]);

                    if (value1 < value2)
                    {                  
                        return true; // string1 is lower
                    }
                    else if (value1 > value2)
                    {
                        return false; // string2 is lower
                    }
                }

                return false; // both strings are equal
            };

            bool needToUpdateApp = CompareNaturalStringsOfAppVersion(currentVersion, remoteVersion);

            if (needToUpdateApp)
            {
                 //Show aleart pop-up to user saying new version is available.
            }
}
e4yzc0pl

e4yzc0pl2#

添加到问题的完整代码,你失败的尝试在OnAppearing
如果LoginPage是您的应用中显示的第一个页面,那么您肯定不希望在检查版本时阻止OnAppearing返回-重要的是让您的应用在启动时尽快显示某些内容
我做了一个“StartupPage”与应用程序/公司标志+“加载中...”。当任何初始化逻辑正在运行时都会显示此信息。
该技术是在后台运行初始化。完成后,转到相应的页面。在您的情况下,请转到以下两个页面之一:

  • 如果是最新的,请转到登录页面。
  • 如果尝试获取商店版本失败,也转到登录页面!
  • 如果有较新版本,请转到通知用户新版本的页面,其中有两个按钮。一个按钮转到App Store,另一个按钮转到登录页面。

StartupPage的OnAppearing:

public partial class StartupPage : ContentPage
{
    protected override void OnAppearing()
    {
        base.OnAppearing();

        // Start background work. IMPORTANT: DO NOT "await" Task.Run itself;
        // let `OnAppearing` return before this work is done.
        Task.Run( async () => await Initialization() );
    }

    // Make sure this is run on a background thread (via Task.Run).
    // REASON: Don't want to delay StartupPage appearing.
    private async Task Initialization()
    {
        // true if there is an update available.
        // false if no update.
        // false if time out or error while checking app version.
        bool appUpdateExists = false;

        try
        {
            // ... your code to check app version
            if (...)
            {
                appUpdateExists = true;
            }
        }
        catch (Exception ex)
        {   // Any failure; assume there is no update, so proceeds to login.
            appUpdateExists = false;
        }

        // Get back to MainThread, before switching to new page.
        MainThread.BeginInvokeOnMainThread( async () =>
        {
            if (appUpdateExists)
                 ... // to UpdateExistsPage.
            else
                 ... // to LoginPage.
        }
    }
}

相关问题