iOS应用的检测更新是绝对会用到的一个功能,这里分享下我的方法。
 
这里使用POST的方式,获取的Data是JSON格式的数据,所以需要解析JSON,这里使用系统的提供的NSJSONSerialization,位于<Foundation/NSJSONSerialization.h>,所以是Foundation Framework的,不用担心忘记加Framework。
 
下面是简单的使用方法,具体请查看Apple Developer,或者本地Orginizer => Documentation
PS:API查询,这里推荐下Dash,在AppStore免费下载,支持iOS、Android、Cocos2d等众多API,且个人感觉速度比较快(= =)
 
代码不多,我就直接贴了:
 
1. app地址 
 
1 // itunes应用查询地址,id为itunes connect的应用ID,这里用的是涂鸦跳跃的ID
2 #define APPSTORE_URL @"http://itunes.apple.com/lookup?id=307727765" 
 
2. 检测更新
 
 1 - (void)update
 2 {
 3     NSURL *url = [NSURL URLWithString:APPSTORE_URL];
 4     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
 5     [request setHTTPMethod:@"POST"];
 6     NSHTTPURLResponse *urlResponse = nil;
 7     NSError *error = nil;
 8     NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
 9     
10 
11     // 使用NSJSONSerialization类来做JSON解析
12     NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptionserror:&error];
13     // 注意返回的对象为NSArray对象,里面包含了APP的各种信息
14     NSArray *infoArray = [dictionary objectForKey:@"results"];
15    
16 //    NSLog(@"dictionary:%@", dictionary);
17 //    NSLog(@"results:%@", infoArray);
18    
19     if ([infoArray count]) {
20         NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
21         NSString *lastVersion = [releaseInfo objectForKey:@"version"];
22         // 自动获取app自身版本号
23         NSString *currentVersion = [NSString stringWithFormat:@"%@",[[NSBundlemainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
24         NSLog(@"get Version:%@", currentVersion);
25        
26         if (![lastVersion isEqualToString:currentVersion]) {
27             self.trackViewURLStr = [releaseInfo objectForKey:@"trackViewUrl"];
28             UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"更新"message:@"有新版本发布,是否前往更新?" delegate:self cancelButtonTitle:@"暂不更新"otherButtonTitles:@"更新", nil];
29             [alert show];
30         }
31     }
32 }

这里的trackViewUrl就是更新的地址啦,有兴趣的话,可以把中间的NSLog注释去掉看下打印的内容,里面会有你想要的~

 

3. 提示对话框

 

1 // 提示对话框按钮响应函数
2 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
3 {
4      // 点击了“更新”
5     if (1 == buttonIndex) {
6         [[UIApplicationsharedApplication] openURL:[NSURLURLWithString:self.trackViewURLStr]];
7     }
8 }

 因为用到了UIAlertView来做提示对话框,所以需要实现UIAlertViewDelegate协议。

 

好了,完成!

posted on 2013-04-25 21:57  流淌的风  阅读(459)  评论(0编辑  收藏  举报