通过iTunes检测更新,使用NSJSONSerialization解析JSON格式版本信息

本文介绍了一种iOS应用中常用的检测更新方法,通过POST请求从iTunes获取JSON格式的应用信息,并利用NSJSONSerialization进行解析。文章提供了完整的示例代码,展示了如何比较应用版本并弹出更新提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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协议。

 

好了,完成!

转载于:https://www.cnblogs.com/evangwt/archive/2013/04/25/3043621.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值