您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 檢測應用版本更新實作教學

編輯:iOS 相關資訊

在應用上線後,如何提示使用者有新版本可以更新,是相當實用的功能。本文示範如何透過 Apple 提供的 iTunes Lookup 介面,取得 App Store 上的最新版本資訊,並與當前版本比對,若有更新則彈出提示框。

實作原理

我們可以透過 iTunes 的 lookup 介面,傳入 App 的 id,取得該應用的相關資訊(其中包含版本號)。接著讀取應用自身的 CFBundleVersion,兩者比對即可判斷是否需要更新。

程式碼示範

- (void)GetUpdate
{
    // 取得當前應用的版本號
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *nowVersion = [infoDict objectForKey:@"CFBundleVersion"];

    // 透過 iTunes lookup 介面取得 App Store 上的資訊(*** 為 App ID)
    NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/lookup?id=***"];
    NSString *file = [NSString stringWithContentsOfURL:url];
    NSLog(@"%@", file);

    // 從回傳的資料中擷取 "version":"1.0" 裡的版本號
    NSRange substr = [file rangeOfString:@"\"version\":\""];
    NSRange substr2 = [file rangeOfString:@"\""
                                 options:NULL
                                   range:NSMakeRange(substr.location + substr.length, 10)];
    NSRange range = {substr.location + substr.length,
                     substr2.location - substr.location - substr.length};
    NSString *newVersion = [file substringWithRange:range];

    // 版本不一致時,彈出更新提示
    if ([nowVersion isEqualToString:newVersion] == NO)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"版本有更新"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"更新", nil];
        [alert show];
    }
}

// 處理提示框的按鈕點擊事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        // 點擊「更新」後,跳轉到 App Store 下載頁面
        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/us/app/qun-xiang-dao/id***?ls=1&mt=8"];
        [[UIApplication sharedApplication] openURL:url];
    }
}

幾點補充說明

這段程式碼把 *** 佔位符替換成你實際的 App ID 即可使用。透過字串擷取的方式從回傳資料中取出版本號,是最直觀的做法。

需要留意的是,字串解析對回傳格式的變化較為脆弱,一旦 Apple 調整了回傳結構,擷取邏輯就可能失效。因此在正式專案中,建議改用 NSJSONSerialization 來解析 lookup 介面回傳的 JSON 資料,會更加穩健可靠。此外,直接跳轉 App Store 時,也可以使用 itms-apps:// 協定,讓使用者更順暢地回到應用商店。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved