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

来源:互联网 发布:抗震神器 知乎 编辑:程序博客网 时间:2024/06/06 07:16
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,这里用的是涂鸦跳跃的ID2 #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)buttonIndex3 {4      // 点击了“更新”5     if (1 == buttonIndex) {6         [[UIApplicationsharedApplication] openURL:[NSURLURLWithString:self.trackViewURLStr]];7     }8 }
复制代码

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

 

好了,完成!



原创粉丝点击