iOS 检查app版本是否要更新 ---站在巨人的肩膀上

来源:互联网 发布:淘宝美工招聘信息深圳 编辑:程序博客网 时间:2024/05/01 20:16

最近做这个检查版本的功能,有一些小心得,和大家分享一下:

  -----------------------------------华丽丽的分割线(下面为巨人)-----------------------------------------------------------------------

如果我们要检测app版本的更新,那么我们必须获取当前运行app版本的版本信息和appstore 上发布的最新版本的信息。


当前运行版本信息可以通过info.plist文件中的bundle version中获取:

[cpp] view plaincopy
  1. NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];  
  2.     CFShow(infoDic);  
  3.       
  4.     NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];  

这样就获取到当前运行的app的版本了


要获取当前app store上的最新的版本,有两种方法,

一、在某特定的服务器上,发布和存储app最新的版本信息,需要的时候向该服务器请求查询。


二、从app store上查询,可以获取到app的作者,连接,版本等。官方相关文档

www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.htm


具体步骤如下:
1,用 POST 方式发送请求:
http://itunes.apple.com/search?term=你的应用程序名称&entity=software

更加精准的做法是根据 app 的 id 来查找:
http://itunes.apple.com/lookup?id=你的应用程序的ID

#define APP_URL http://itunes.apple.com/lookup?id=你的应用程序的ID

你的应用程序的ID 是 itunes connect里的 Apple ID

2,从获得的 response 数据中解析需要的数据。因为从 appstore 查询得到的信息是 JSON 格式的,所以需要经过解析。解析之后得到的原始数据就是如下这个样子的:
{  
    resultCount = 1;  
    results =     (  
                {  
            artistId = 开发者 ID;  
            artistName = 开发者名称; 
            price = 0; 
            isGameCenterEnabled = 0;  
            kind = software;  
            languageCodesISO2A =             (  
                EN  
            ); 
            trackCensoredName = 审查名称;  
            trackContentRating = 评级;  
            trackId = 应用程序 ID;  
            trackName = 应用程序名称";  
            trackViewUrl = 应用程序介绍网址;  
            userRatingCount = 用户评级;  
            userRatingCountForCurrentVersion = 1;  
            version = 版本号;  
            wrapperType = software; 
      }  
    );  
}  

然后从中取得 results 数组即可,具体代码如下所示:

NSDictionary *jsonData = [dataPayload JSONValue];  
NSArray *infoArray = [jsonData objectForKey:@"results"];  
NSDictionary *releaseInfo = [infoArray objectAtIndex:0];  
NSString *latestVersion = [releaseInfo objectForKey:@"version"];  
NSString *trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];  

如果你拷贝 trackViewUrl 的实际地址,然后在浏览器中打开,就会打开你的应用程序在 appstore 中的介绍页面。当然我们也可以在代码中调用 safari 来打开它。
UIApplication *application = [UIApplication sharedApplication];  
[application openURL:[NSURL URLWithString:trackViewUrl]];  


代码如下:

-(void)onCheckVersion

{

    NSDictionary *infoDic = [[NSBundle mainBundleinfoDictionary];

    //CFShow((__bridge CFTypeRef)(infoDic));

    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];


    NSString *URL = @"http://itunes.apple.com/lookup?id=你的应用程序的ID";

    NSMutableURLRequest *request = [[NSMutableURLRequest allocinit];

    [request setURL:[NSURL URLWithString:URL]];

    [request setHTTPMethod:@"POST"];

    NSHTTPURLResponse *urlResponse = nil;

    NSError *error = nil;

    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];

    

    NSString *results = [[NSString allocinitWithBytes:[recervedData byteslength:[recervedData lengthencoding:NSUTF8StringEncoding];

    NSDictionary *dic = [results JSONValue];(请大家注意这里)

    NSArray *infoArray = [dic objectForKey:@"results"];

    if ([infoArray count]) {

        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];

        NSString *lastVersion = [releaseInfo objectForKey:@"version"];

        

        if (![lastVersion isEqualToString:currentVersion]) {

            //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];

            UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"更新" message:@"有新的版本更新,是否前往更新?" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新"nil];

            alert.tag = 10000;

            [alert show];

        }

        else

        {

            UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"更新" message:@"此版本为最新版本"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nilnil];

            alert.tag = 10001;

            [alert show];

        }

    }

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (alertView.tag==10000) {

        if (buttonIndex==1) {

            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com"];

            [[UIApplication sharedApplication]openURL:url];

        }

    }

}

---------------------------------over-------------------------------------------

下面是我自己的见解:

  不知道大家注意到巨人代码中粗体的部分没有,没有的话可以去看看,JSONValue这个方法在生生的引入中会报警告,然后会造成项目崩溃,度娘说要引入json-framework才可以使用,而我在

1、从https://github.com/stig/json-framework/中下载json框架:json-framework

2、解压下载的包,将class文件夹下的所有文件导入到当前工程下。

3、在使用的文件中加入导入语句 :#import "SBJson.h"

4、将json字符串转为NSDictionary对象。

这种方法里并没有找到我想要的东西,因此我转向了使用iOS自带的解析json的类解析得到了目标dictionary,代码如下

  id jsonObject = [NSJSONSerialization JSONObjectWithData:recervedData options:NSJSONReadingAllowFragments error:&error];

     if ([jsonObject isKindOfClass:[NSDictionary class]]){

          NSDictionary *dic = (NSDictionary *)jsonObject;

        NSArray *infoArray = [dic objectForKey:@"results"];

    if ([infoArray count]) {

        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];

        NSString *lastVersion = [releaseInfo objectForKey:@"version"];

        

        if (![lastVersion isEqualToString:currentVersion]) {

            //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];

            UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"更新" message:@"有新的版本更新,是否前往更新?" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新"nil];

            alert.tag = 10000;

            [alert show];

        }

        else

        {

            UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"更新" message:@"此版本为最新版本"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nilnil];

            alert.tag = 10001;

            [alert show];

        }

    }


}

nslog可知原代码中results是一个 头尾都有3个换行中间是字典的字符串,而我解析过后的dic是一个纯字典对象。

下面是ios原生解析json的简单使用:

1。数据源是NSData类型的,也可以是NSString类型的,但是NSString类型的可以转换为NSData类型的.

     NSString *responseString;

    NSData *da= [responseString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error = nil;

     id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

     if ([jsonObject isKindOfClass:[NSDictionary class]]){

     NSDictionary *dictionary = (NSDictionary *)jsonObject;

     NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);

     }else if ([jsonObject isKindOfClass:[NSArray class]]){

     NSArray *nsArray = (NSArray *)jsonObject;

     NSLog(@"Dersialized JSON Array = %@", deserializedArray);

     } else {

     NSLog(@"An error happened while deserializing the JSON data.");

     }

 2,读取项目下的文件代码。

 

    NSString *mainBundleDirectory=[[NSBundle mainBundle] bundlePath];

    NSString *path=[mainBundleDirectory stringByAppendingPathComponent:@"123.txt"];

    NSURL *url=[NSURL fileURLWithPath:path];

    NSData *data = [[NSDataalloc] initWithContentsOfURL:url];

   NSString* aStr=[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding]; 

希望能对大家有所帮助。



0 0