想主動提醒使用者「有新版本」,最可靠的方式不是自己猜,而是去問 App Store。做法是呼叫 iTunes 的 lookup 介面取得線上版號,跟本地 bundle 的版本比大小,若線上較新就彈出提示。
/**
* 檢測軟體是否需要升級
*/
-(void)checkVersion
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
@"https://itunes.apple.com/cn/lookup?id=%i", iFeverAPPID]];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request setUseCookiePersistence:YES];
[request setDelegate:self];
[request setDidFailSelector:@selector(getVersionRequestFailed:)];
[request setDidFinishSelector:@selector(getVersionRequestSuccess:)];
[request startAsynchronous];
}
-(void)getVersionRequestFailed:(ASIHTTPRequest *)request1
{
NSLog(@"從 AppStore 獲取版本信息失敗!!");
}
-(void)getVersionRequestSuccess:(ASIHTTPRequest *)request1
{
NSString *newVersion = nil;
NSData *responseData = [request1 responseData];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments
error:nil];
NSArray *resultArray = [dic objectForKey:@"results"];
for (id config in resultArray) {
newVersion = [config valueForKey:@"version"];
}
if (newVersion) {
NSLog(@"通過 AppStore 獲取的版本號是:%@", newVersion);
}
// 取得本地版本號
NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSString *msg = [NSString stringWithFormat:
@"你當前的版本是 V%@,發現新版本 V%@,是否下載新版本?", localVersion, newVersion];
if ([newVersion floatValue] > [localVersion floatValue]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"升級提示!"
message:msg
delegate:self
cancelButtonTitle:@"下次再說"
otherButtonTitles:@"現在升級", nil];
alert.tag = kVersionNeedUpdateAlertTag;
[alert show];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == kVersionNeedUpdateAlertTag) {
if (buttonIndex == 1) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:
@"https://itunes.apple.com/cn/app/id%i?mt=8", iFeverAPPID]];
[[UIApplication sharedApplication] openURL:url];
}
}
}
另一種寫法是直接開 itms-apps:// 開頭的 iTunes 連結,但實測常常跳出「無法連接到 iTunes」的提示,不太建議使用。
把 App ID 代入這個網址就能直接在瀏覽器看到 JSON:
https://itunes.apple.com/cn/lookup?id=465039730
floatValue 對「1.10」與「1.9」會判錯,因為 1.10 反而小於 1.9。請改用 compare:options:NSNumericSearch 逐段比對。SKStoreProductViewController,使用者能直接在 App 內完成更新,不必跳出到 App Store。