iOS 開發筆記 - 開發中如何實現自動檢測更新APP


1.獲取當前項目APP版本號

2.拿到AppStore項目版本號

3.對比版本號,實現更新功能

直接上代碼:

#import "ViewController.h"
//1一定要先配置自己項目在商店的APPID,配置完最好在真機上運行才能看到完全效果哦
#define STOREAPPID @"1080182980"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //一句代碼實現檢測更新
    [self hsUpdateApp];
}

/**
 *  天朝專用檢測app更新
 */
-(void)hsUpdateApp
{
    //2先獲取當前工程項目版本號
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    
    //3從網絡獲取appStore版本號
    NSError *error;
    NSData *response = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",STOREAPPID]]] returningResponse:nil error:nil];
    if (response == nil) {
        NSLog(@"你沒有連接網絡哦");
        return;
    }
    NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"hsUpdateAppError:%@",error);
        return;
    }
    NSArray *array = appInfoDic[@"results"];
    NSDictionary *dic = array[0];
    NSString *appStoreVersion = dic[@"version"];
    //打印版本號
    NSLog(@"當前版本號:%@\n商店版本號:%@",currentVersion,appStoreVersion);
    //4當前版本號小於商店版本號,就更新
    if([currentVersion floatValue] < [appStoreVersion floatValue])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"檢測到新版本(%@),是否更新?",appStoreVersion] delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"更新",nil];
        [alert show];
    }else{
        NSLog(@"版本號好像比商店大噢!檢測到不需要更新");
    }

}

- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //5實現跳轉到應用商店進行更新
    if(buttonIndex==1)
    {
        //6此處加入應用在app store的地址,方便用戶去更新,一種實現方式如下:
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/id%@?ls=1&mt=8", STOREAPPID]];
        [[UIApplication sharedApplication] openURL:url];
    }
}

@end

 

相關博客:http://www.cnblogs.com/wolfhous/p/5389929.html 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM