码迷,mamicode.com
首页 > 移动开发 > 详细

ios监听版本更新

时间:2017-11-20 17:57:16      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:状态   sda   objects   监听   multi   reserve   cat   字典   afn   

技术分享图片
//
//  UpdatedAppManager.h
//  PengCunPatrol
//
//  Created by YuFly on 2017/11/10.
//  Copyright ? 2017年 YuFly. All rights reserved.
//

#import <Foundation/Foundation.h>
@interface UpdatedAppManager : NSObject
+ (UpdatedAppManager *)sharedManager;

//从appstore获取版本
- (void)checkForUpdatesFromAppStoreWithIsEnforce:(BOOL)isEnforce
                                     success:(void (^)(id,id,id))success
                                     failure:(void (^)(id))failure;


//从自己服务端获取版本
- (void)checkForUpdatesFromMyServiceWithUrlString:(NSString *)urlString
                                          success:(void (^)(id,id,id))success
                                          failure:(void (^)(id))failure;
@end
View Code
技术分享图片
//
//  UpdatedAppManager.m
//  PengCunPatrol
//
//  Created by YuFly on 2017/11/10.
//  Copyright ? 2017年 YuFly. All rights reserved.
//

#import "UpdatedAppManager.h"
#import "NetService.h"


#define APPSTOREURL @"http://itunes.apple.com/cn/lookup?bundleId=@bundleId@"

@implementation UpdatedAppManager
static UpdatedAppManager *sharedManager = nil;

+ (UpdatedAppManager *)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[UpdatedAppManager alloc]init];
    });
    return sharedManager;
}
/**
 从appstore获取版本信息判断更新

 @param isEnforce 是否强制更新
 @param success 成功回调字典,三个参数 1.isUpdate 是否要更新 2.content 更新内容 3.isEnforce 是否强制更新
 @param failure 失败回调
 */
- (void)checkForUpdatesFromAppStoreWithIsEnforce:(BOOL)isEnforce
                                        success:(void (^)(id,id,id))success
                                        failure:(void (^)(id))failure{
    
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    NSString *CFBundleIdentifier         = [infoDic objectForKey:@"CFBundleIdentifier"];
    NSString *CFBundleShortVersionString = [infoDic objectForKey:@"CFBundleShortVersionString"];
    NSString *url = [APPSTOREURL stringByReplacingOccurrencesOfString:@"@bundleId@" withString:CFBundleIdentifier];
    [self checkForUpdatesWithUrlString:url success:^(id result) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        NSArray *resultss   = [resultDic objectForKey:@"results"];
        if(resultss.count==0)
            return ;
        NSDictionary *results = resultss.firstObject;
        NSString *version       = [results objectForKey:@"version"]?[results objectForKey:@"version"]:@"1.0.1";
        NSString *releaseNotes  = [results objectForKey:@"releaseNotes"]?[results objectForKey:@"releaseNotes"]:@"";
        NSArray *versionArray   = [version componentsSeparatedByString:@"."];
        NSArray *localVersionArray = [CFBundleShortVersionString componentsSeparatedByString:@"."];
        NSInteger length = versionArray.count>=localVersionArray.count?localVersionArray.count:versionArray.count;
        BOOL isUpdate = NO;
        for(NSInteger i=0;i<length;i++){
            NSInteger n = [[versionArray objectAtIndex:i] integerValue];
            NSInteger m = [[localVersionArray objectAtIndex:i] integerValue];
            if(n>m){
                isUpdate=YES;
                break;
            }
        }
        if(!isUpdate&&versionArray.count>localVersionArray.count)
            isUpdate=YES;
        if(success)
            success(@(isUpdate),@(isEnforce),releaseNotes);
        
    } failure:^(id error) {
        if(failure)
            failure(error);
    }];
}



/**
 从自己服务端获取版本

 @param urlString 自己服务端接口
 @param success 成功回调字典,包括 key:RESULT value:字典(包括的key有 版本号:version  更新内容:releaseNotes 是否强制更新:isEnforce)
 @param failure 失败回调
 */
- (void)checkForUpdatesFromMyServiceWithUrlString:(NSString *)urlString
                                          success:(void (^)(id,id,id))success
                                          failure:(void (^)(id))failure{
    
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    NSString *CFBundleIdentifier         = [infoDic objectForKey:@"CFBundleIdentifier"];
    NSString *CFBundleShortVersionString = [infoDic objectForKey:@"CFBundleShortVersionString"];
    NSString *url = [APPSTOREURL stringByReplacingOccurrencesOfString:@"@bundleId@" withString:CFBundleIdentifier];
    [self checkForUpdatesWithUrlString:url success:^(id result) {
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
        NSDictionary *results= [resultDic objectForKey:@"RESULT"];
        
        NSString *version       = [results objectForKey:@"version"]?[results objectForKey:@"version"]:@"1.0.1";
        NSString *releaseNotes  = [results objectForKey:@"releaseNotes"]?[results objectForKey:@"releaseNotes"]:@"";
        BOOL      isEnforce     = [[results objectForKey:@"isEnforce"] boolValue]?[[results objectForKey:@"isEnforce"] boolValue]:NO;
        NSArray *versionArray   = [version componentsSeparatedByString:@"."];
        NSArray *localVersionArray = [CFBundleShortVersionString componentsSeparatedByString:@"."];
        NSInteger length = versionArray.count>=localVersionArray.count?localVersionArray.count:versionArray.count;
        BOOL isUpdate = NO;
        for(NSInteger i=0;i<length;i++){
            NSInteger n = [[versionArray objectAtIndex:i] integerValue];
            NSInteger m = [[localVersionArray objectAtIndex:i] integerValue];
            if(n>m){
                isUpdate=YES;
                break;
            }
        }
        if(!isUpdate&&versionArray.count>localVersionArray.count)
            isUpdate=YES;
        if(success)
            success(@(isUpdate),@(isEnforce),releaseNotes);
        
    } failure:^(id error) {
        if(failure)
            failure(error);
    }];
    
    
}


- (void)checkForUpdatesWithUrlString:(NSString *)url
                             success:(void (^)(id))success
                             failure:(void (^)(id))failure{
    
    [NetService requestWithURLString:url parameters:nil type:ServiceTypeGet success:^(id result) {
        if(success)
            success(result);
    } failure:^(id error) {
        if(failure)
            failure(error);
    }];
    
}

@end
View Code
技术分享图片
//
//  NetService.h
//  PengCunPatrol
//
//  Created by YuFly on 2017/10/24.
//  Copyright ? 2017年 YuFly. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AFNetworking.h"
typedef NS_ENUM(NSUInteger,ServiceType) {
    /**
     *  get请求
     */
    ServiceTypeGet = 0,
    /**
     *  post请求
     */
    ServiceTypePost
};
@interface NetService : NSObject


/**
 网络请求

 @param URLString url
 @param parameters 参数
 @param type 请求类型
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                        type:(ServiceType)type
                     success:(void (^)(id result))success
                     failure:(void (^)(id error))failure;


/**
 上传多媒体文件

 @param url url
 @param parameters 参数
 @param dataArray 多媒体文件
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)uploadMultimediaWithPostUrl:(NSString *)url
                         parameters:(id)parameters
                          dataArray:(NSArray *)dataArray
                            success:(void (^)(id))success
                            failure:(void (^)(id))failure;

@end
View Code
技术分享图片
//
//  NetService.m
//  PengCunPatrol
//
//  Created by YuFly on 2017/10/24.
//  Copyright ? 2017年 YuFly. All rights reserved.
//

#import "NetService.h"
#import "AFNetState.h"
@implementation NetService
- (instancetype)init{
    if(self=[super init]){
    }
    return self;
}

+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                        type:(ServiceType)type
                     success:(void (^)(id))success
                     failure:(void (^)(id))failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    manager.requestSerializer.timeoutInterval = 30;
    URLString=[URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    switch (type) {
        case ServiceTypeGet:
        {
            
            [manager GET:URLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;// 关闭网络指示器
                    });
                    success(responseObject);
                    
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
                if (failure) {
                    if([AFNetState netState].networkState==0){
                        failure(@"网络错误,请检查网络后重试");
                    }else{
                        failure(@"请求失败");
                    }
                }
            }];
        }
            break;
        case ServiceTypePost:
        {
            
            [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;// 关闭网络指示器
                    });
                    success(responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    if([AFNetState netState].networkState==0){
                        failure(@"网络错误,请检查网络后重试");
                    }else{
                        failure(@"请求失败");
                    }
                }
            }];
            
        }
            break;
    }
    
}

+ (void)uploadMultimediaWithPostUrl:(NSString *)url
                         parameters:(id)parameters
                               dataArray:(NSArray *)dataArray
                            success:(void (^)(id))success
                            failure:(void (^)(id))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < dataArray.count; i++)
        {
            NSDictionary *resultDict = dataArray[i];
            if (resultDict[@"image"])
            {
                //图片
                [formData appendPartWithFileData:resultDict[@"image"] name:@"Filedata" fileName:resultDict[@"fileName"] mimeType:@"image/jpeg"];
            }
            else if (resultDict[@"mov"])
            {
                //文件
                NSData* videoData = [NSData dataWithContentsOfURL:resultDict[@"mov"]];
                [formData appendPartWithFileData:videoData name:@"Filedata" fileName:resultDict[@"fileName"] mimeType:@"media"];
            }
            else
            {
                NSData* vioceData = resultDict[@"voice"];
                [formData appendPartWithFileData:vioceData name:@"Filedata" fileName:resultDict[@"fileName"] mimeType:@"media"];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *json = [[NSString alloc]initWithData:responseObject
                                              encoding:NSUTF8StringEncoding];
        json = [json stringByReplacingOccurrencesOfString:@"+" withString:@" "];
        json = [json stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSData *data;
        NSArray *result;
        data   = [json dataUsingEncoding:NSUTF8StringEncoding];
        result = [NSJSONSerialization JSONObjectWithData:data
                                                 options:0
                                                   error:nil];
        if(success)
            success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure)
            failure(@"文件上传失败,请重新上传");
        
    }];
    
}


@end
View Code
技术分享图片
//
//  AFNetState.h
//  Standardization
//
//  Created by strong on 17/1/20.
//  Copyright ? 2017年 strong. All rights reserved.
//

#import <AFNetworking/AFNetworking.h>

@interface AFNetState : AFHTTPSessionManager
+ (instancetype)netState;
@property (nonatomic,assign)NSInteger networkState;

@end
View Code
技术分享图片
//
//  AFNetState.m
//  Standardization
//
//  Created by strong on 17/1/20.
//  Copyright ? 2017年 strong. All rights reserved.
//

#import "AFNetState.h"

@implementation AFNetState
static AFNetState *netState = nil;
+ (AFNetState *)netState
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
                      netState = [[AFNetState alloc]init];
                      [netState nowNetState];
                  });
    return netState;
}

//网络状态
- (void)nowNetState
{
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
    {
        _networkState = status;
    }];
    [reachabilityManager startMonitoring];
}

@end
View Code

 

ios监听版本更新

标签:状态   sda   objects   监听   multi   reserve   cat   字典   afn   

原文地址:http://www.cnblogs.com/YuFly-lyx/p/7867110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!