App 上線後,若能在啟動時提醒使用者有新版本可下載,往往能有效提升升級率。最簡單且不需自建後端的做法,是直接查詢 Apple 官方的 iTunes Lookup 服務,拿回目前 App Store 上的最新版本號,再與 App 內建的版本比對。
整體步驟只有四步:讀取本地版本、發出查詢、解析回應中的版本字串、比對後決定是否提示。
-(void)GetUpdate {
// 1. 取得 App 自身的版本號
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *nowVersion = [infoDict objectForKey:@"CFBundleVersion"];
// 2. 查詢 iTunes(*** 處替換為你的 App ID)
NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/lookup?id=***"];
NSString *file = [NSString stringWithContentsOfURL:url];
NSLog(@"%@", file);
// 3. 從回應中擷取 "version":"x.x.x" 的內容
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];
// 4. 版本不同就提示
if (![nowVersion isEqualToString:newVersion]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
message:@"版本有更新"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"更新", nil];
[alert show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/app/id***?mt=8"];
[[UIApplication sharedApplication] openURL:url];
}
}
第一,上面用字串 rangeOfString: 硬擷取版本號的做法雖然直觀,但對回應格式變動相當脆弱。若使用 iOS 5 以後的系統,改用 NSJSONSerialization 解析成 NSDictionary,再取 results 陣列第一個元素的 version 欄位,會穩健得多。
第二,版本比較不要只用 isEqualToString: 判斷「不同」,否則本地版本較新時也會誤報有更新。建議把版本號拆成數字元件逐段比較。
第三,stringWithContentsOfURL: 是同步且在主執行緒進行的網路請求,會凍結 UI。正式環境請改用非同步連線或背景佇列。