美文网首页
一个跟AppStore交互的工具类

一个跟AppStore交互的工具类

作者: 永远都能 | 来源:发表于2016-03-27 00:34 被阅读147次

    1.这是AppStoreHelper.h

    //
    //  AppStoreHelper.h
    //  018_跳转AppStore
    //
    //  Created by ZYN on 16/3/19.
    //  Copyright © 2016年 Yongneng Zheng. All rights reserved.
    //  跟AppStore交互的一个类
    
    
    #import <UIKit/UIKit.h>
    
    /** 检查完成时*/
    typedef void(^checkVersionCompletedBlock)(BOOL isNeddUpdate , NSString *updateContent);
    /** 网络请求数据失败时*/
    typedef void(^FailBlock) (NSError *error);
    
    @interface AppStoreHelper : NSObject
    
    /**
     *  手动检查版本
     *
     *  @param AppStoreID     商店ID
     *  @param completedBlock 检查完成
     *  @param failBlock      检查失败
     */
    + (void)checkVersionWithAppStoreID:(NSString *)AppStoreID Completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock;
    
    /**
     *  自动检查
     *
     *  @param AppStoreID     商店ID
     *  @param seconds        自动检查间隔(秒)
     *  @param completedBlock 检查完成
     *  @param failBlock      检查失败
     */
    + (void)checkVersionAutoWithAppStoreID:(NSString *)AppStoreID CheckTimeInterval:(NSInteger)seconds completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock;
    
    /**
     *  跳转到苹果商店下载页面
     *
     *  @param AppStoreID
     */
    + (void)intentAppStoreDownLoad:(NSString *)AppStoreID;
    
    /**
     *  跳转到苹果商店评论页面
     *
     *  @param AppStoreID
     */
    + (void)intentAppStoreComments:(NSString *)AppStoreID;
    
    @end
    
    

    2.这是AppStoreHelper.m

    //
    //  AppStoreHelper.m
    //  018_跳转AppStore
    //
    //  Created by ZYN on 16/3/19.
    //  Copyright © 2016年 Yongneng Zheng. All rights reserved.
    //
    
    #import "AppStoreHelper.h"
    
    @implementation AppStoreHelper
    
    
    + (void)checkVersionAuto:(BOOL)autoCheck apptoreID:(NSString *)appStoreID checkTimeInterval:(NSInteger)seconds completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock{
        
        BOOL isCanCheck = NO;
        long long timeInterval = [NSDate date].timeIntervalSince1970;
        NSString *time = [[NSUserDefaults standardUserDefaults] objectForKey:@"checkVersionTime"];
        if (!time) {
           //保存当前的时间戳
            [[NSUserDefaults standardUserDefaults] setObject:@(timeInterval) forKey:@"checkVersionTime"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else{
            if (autoCheck) {//自动检查时间
                if (timeInterval >= [time longLongValue] + seconds) {
                    isCanCheck = YES;
                    //保存当前的时间戳
                    [[NSUserDefaults standardUserDefaults] setObject:@(timeInterval) forKey:@"checkVersionTime"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                } ;
            }else{
                isCanCheck = YES;
            }
        }
        
        //不需要检查
        if (!isCanCheck) return;
        
        
        [self checkVersionWithRequestHttp:autoCheck apptoreID:appStoreID checkTimeInterval:timeInterval completion:completedBlock fail:failBlock];
        
    
    }
    /**
     * 请求网络数据 进行判断    (目前是用Appstore的版本信息,也可以改为自己服务器的信息)
     */
    + (void)checkVersionWithRequestHttp:(BOOL)autoCheck apptoreID:(NSString *)appStoreID checkTimeInterval:(long long)seconds completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock{
        NSString *currentVersion = [self.class getCurrentVersion];
        //请求AppStore获取版本和版本提示信息
        NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",appStoreID]];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *  data, NSURLResponse *  response, NSError *  error) {
            
            if (error) {
                if (failBlock) {
                    failBlock(error);
                }
                return;
            }
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            NSArray *infoArray = [dic objectForKey:@"results"];
            
            if ([infoArray isKindOfClass:[NSArray class]] && [infoArray count]>0) {
                
                //商店的版本号
                NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
                NSString *appstoreVersion = [releaseInfo objectForKey:@"version"];
                
                BOOL isNeedUpdate = [self.class checkVersionIsNeedUpdateClientV:currentVersion serverV:appstoreVersion];
                if (isNeedUpdate) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (completedBlock) {
                            completedBlock(YES,releaseInfo[@"releaseNotes"]);
                        }
                    });
                }else{
                    //一般 只有不是 自动检查 才会 提示 当前是 最新版本
                    if (!autoCheck) {
                        if (completedBlock) {
                            completedBlock(NO,@"当前是最新版本啦~");
                        }
                    };
                    
                };
            }
        }];
        //开始请求
        [dataTask resume];
        
    }
    
    + (void)checkVersionWithAppStoreID:(NSString *)AppStoreID Completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock{
        
        return [self.class checkVersionAuto:NO apptoreID:AppStoreID checkTimeInterval:0 completion:completedBlock fail:failBlock];
    }
    
    +(void)checkVersionAutoWithAppStoreID:(NSString *)AppStoreID CheckTimeInterval:(NSInteger)seconds completion:(checkVersionCompletedBlock)completedBlock fail:(FailBlock)failBlock{
    
        return [self.class checkVersionAuto:YES apptoreID:AppStoreID checkTimeInterval:seconds completion:completedBlock fail:failBlock];
    }
    
    /**
     *  跳转到苹果商店下载页面
     *
     *  @param AppStoreID
     */
    + (void)intentAppStoreDownLoad:(NSString *)AppStoreID{
    
        //苹果商店下载页面
        NSString*str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",AppStoreID];
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:str]];
    
    }
    /**
     *  跳转苹果商店评论
     *
     *  @param AppStoreID
     */
    + (void)intentAppStoreComments:(NSString *)AppStoreID{
        
        NSString*str = [NSString stringWithFormat:
                        @"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",AppStoreID];
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:str]];
    
    }
    
    
    /**
     *  判断是否需要更新
     *
     *  @param clientVer 当前版本号
     *  @param serverVer 服务端的版本号
     *
     *  @return YES:需要更新 NO:不需要更新
     */
    + (BOOL)checkVersionIsNeedUpdateClientV:(NSString *)clientVer
                                    serverV:(NSString *)serverVer
    {
       
        NSArray *clientArray = [clientVer componentsSeparatedByString:@"."];
        NSArray *serverArray = [serverVer componentsSeparatedByString:@"."];
        NSInteger count =
        ([clientArray count] > [serverArray count]) ? [clientArray count] : [serverArray count];
        
        for (int i = 0; i < count; i++) {
            NSString *clientString = i < [clientArray count] ? [clientArray objectAtIndex:i] : @"0";
            NSString *serverString = i < [serverArray count] ? [serverArray objectAtIndex:i] : @"0";
            if ([clientString intValue] < [serverString intValue]) {
                return YES;
            }else if ([clientString intValue] > [serverString intValue]){
                return NO;
            }
        }
        return NO;
    }
    
    /**
     *  获取当前的版本号
     *
     *  @return 版本号  1.0.0
     */
    + (NSString *)getCurrentVersion{
    
        return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        
    };
    
    @end
    
    

    说明一下: 网络请求用的是NSURLSession是iOS7以上才有的。

    3.用例:
    (1)AppDelegate.m

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
      
        [AppStoreHelper checkVersionAutoWithAppStoreID:@"444934666" CheckTimeInterval:10 completion:^(BOOL isNeddUpdate, NSString *updateContent) {
            if (isNeddUpdate) {
                [[[UIAlertView alloc]initWithTitle:@"版本更新" message:[NSString stringWithFormat:@"更新内容:\n%@", updateContent] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil] show];
            }else{
                [[[UIAlertView alloc]initWithTitle:@"提示" message:updateContent delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            }
        } fail:^(NSError *error) {
            [[[UIAlertView alloc]initWithTitle:@"提示" message:@"很遗憾检查失败哦~" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }];
    }
    
    

    (2)ViewController.m

    - (IBAction)checkVersion:(id)sender {
        
        [AppStoreHelper checkVersionWithAppStoreID:AppStoreID2 Completion:^(BOOL isNeddUpdate, NSString *updateContent) {
            if (isNeddUpdate) {
                [[[UIAlertView alloc]initWithTitle:@"版本更新" message:[NSString stringWithFormat:@"更新内容:\n%@", updateContent] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil] show];
            }else{
                [[[UIAlertView alloc]initWithTitle:@"提示" message:updateContent delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            }
        } fail:^(NSError *error) {
            [[[UIAlertView alloc]initWithTitle:@"提示" message:@"很遗憾检查失败哦~" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }];
    }
    #pragma mark - UIAlertViewDelegate
    -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        
        if (buttonIndex == 1) {
            [AppStoreHelper intentAppStoreDownLoad:AppStoreID2];
        }
    
    }
    - (IBAction)Intent:(id)sender {
        
        //[[[UIAlertView alloc]initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"残忍拒绝!" otherButtonTitles:@"给个好评啦~",@"我要吐槽~",nil]show];
        
        [AppStoreHelper intentAppStoreComments:AppStoreID2];
        
        
    }
    

    相关文章

      网友评论

          本文标题:一个跟AppStore交互的工具类

          本文链接:https://www.haomeiwen.com/subject/etodlttx.html