一行代码搞定
不影响上线
demo地址:点击打开链接
相关代码:
VersionUpdateTool.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface VersionUpdateTool : NSObject
+(VersionUpdateTool *)sharedInstance;
-(void)VersionUpdate_appStoreID:(NSString *)appStoreID;
@end
VersionUpdateTool.m
#import "VersionUpdateTool.h"
@interface VersionUpdateTool ()
@property(nonatomic,strong)NSDictionary *info;
@end
@implementation VersionUpdateTool
-(instancetype)init {
if (self = [super init]) {
}
return self;
}
+(VersionUpdateTool *)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id Tool = nil;
dispatch_once(&pred, ^{
Tool = [[self alloc] init];
});
return Tool;
}
-(BOOL)isNeedUpdate:(NSString *)appstoreVersion curVersion:(NSString *)curVersion {
NSArray *curVerArr = [curVersion componentsSeparatedByString:@"."];
NSArray *appstoreVerArr = [appstoreVersion componentsSeparatedByString:@"."];
BOOL needUpdate = NO;
//比较版本号大小
int maxv = (int)MAX(curVerArr.count, appstoreVerArr.count);
int cver = 0;
int aver = 0;
for (int i = 0; i < maxv; i++) {
if (appstoreVerArr.count > i) {
aver = [NSString stringWithFormat:@"%@",appstoreVerArr[i]].intValue;
}
else{
aver = 0;
}
if (curVerArr.count > i) {
cver = [NSString stringWithFormat:@"%@",curVerArr[i]].intValue;
}
else{
cver = 0;
}
if(aver != cver) {
if (aver > cver) {
needUpdate = YES;
}else {
needUpdate = NO;
}
return needUpdate;
}
}
return needUpdate;
}
-(void)VersionUpdate_appStoreID:(NSString *)appStoreID{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",appStoreID]]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *arr = dic[@"results"];
if (arr.count > 0) {
self.info = arr[0];
NSString *appstoreVersion = self.info[@"version"];
NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if ([self isNeedUpdate:appstoreVersion curVersion:curVersion]){
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发现新版本" message:[NSString stringWithFormat:@"version %@ \n\n%@",appstoreVersion,self.info[@"releaseNotes"]] delegate:self cancelButtonTitle:@"以后再说" otherButtonTitles:@"立即更新", nil];
[alert show];
});
}
}
}
}];
[task resume];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.info[@"trackViewUrl"]]];
}
}
@end