您的位置:首页 > 移动开发 > IOS开发

iOS版本更新

2019-02-20 10:55 20 查看

最近,应项目需求,简单写了一个版本更新的提示,有需要的码友可以去下载看看,实现起来比较简单。

效果图

首先是请求appStore上这个app的最新版本信息

NSURL *appStoreUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@", APPID]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:appStoreUrl];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

然后根据相关逻辑处理数据
这个里边主要是富文本编辑修改了下alertVC的title跟message显示的格式,处理下逻辑

if (!error) {
NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",appInfoDic);
if ([appInfoDic[@"results"] count] == 0) {
NSLog(@"暂无版本信息");
return ;
}
NSDictionary *messageDic = appInfoDic[@"results"][0];
//版本
NSString *appVersionStr = messageDic[@"version"];
//更新内容
NSString *releaseNotes = messageDic[@"releaseNotes"];
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"] == nil ||[[NSUserDefaults standardUserDefaults] objectForKey:@"newVersion"] != appVersionStr) {
[[NSUserDefaults standardUserDefaults] setObject:appVersionStr forKey:@"newVersion"];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"AppUpdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
if (appVersionStr == nil || [self getCurrentVersion] == appVersionStr || [[NSUserDefaults standardUserDefaults] boolForKey:@"AppUpdate"]){
return;
}
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"有新版本更新\n%@\n",appVersionStr] message:releaseNotes preferredStyle:UIAlertControllerStyleAlert];
UIView *messageParentView = [self getParentViewOfTitleAndMessageFromView:alertVC.view];
if (messageParentView && messageParentView.subviews.count > 1) {
UILabel *messageLb = messageParentView.subviews[1];
messageLb.textAlignment = NSTextAlignmentLeft;
}
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"稍后更新" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
NSString *alertVCTitle = [NSString stringWithFormat:@"有新版本更新\n%@",appVersionStr];
NSMutableAttributedString *alertVCAttributedTitle = [self changeStrWith:alertVCTitle range:NSMakeRange(6, alertVCTitle.length - 6) strColor:[UIColor lightGrayColor] strFont:[UIFont systemFontOfSize:16]];
//修改提示框标题字体
[alertVC setValue:alertVCAttributedTitle forKey:@"attributedTitle"];
NSMutableAttributedString *alertVCAttributedMessage = [self changeStrWith:releaseNotes range:NSMakeRange(0, releaseNotes.length) strColor:[UIColor darkGrayColor] strFont:[UIFont systemFontOfSize:15.0]];
//修改提示信息格式
[alertVC setValue:alertVCAttributedMessage forKey:@"attributedMessage"];

//获取当前控制器
UIViewController *currentVc = [self activityViewController];

UIAlertAction *conformAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
NSDictionary *parameters = @{SKStoreProductParameterITunesItemIdentifier : APPID,
SKStoreProductParameterAffiliateToken : [NSString string],
SKStoreProductParameterCampaignToken : [NSString string]
};
[storeViewController loadProductWithParameters:parameters completionBlock:^(BOOL result, NSError *error) {

if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[currentVc presentViewController:storeViewController animated:YES completion:^{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AppUpdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}];
});
}else{
NSLog(@"%@",error);
}
}];

}else{
NSString *appStroeStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/cn/app/id%@?l=en&mt=8", APPID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStroeStr]];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AppUpdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
[alertVC addAction:cancleAction];
[alertVC addAction:conformAction];
dispatch_async(dispatch_get_main_queue(), ^{
[currentVc presentViewController:alertVC animated:YES completion:nil];
});
}
}];
[task resume];
});

里边用运了程序内部调用appStore的方法,苹果有相关的框架StoreKit,里边的控制器SKStoreProductViewController就是展示界面,我们可以只传相应的appID进去就行

if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
NSDictionary *parameters = @{SKStoreProductParameterITunesItemIdentifier : APPID,
SKStoreProductParameterAffiliateToken : [NSString string],
SKStoreProductParameterCampaignToken : [NSString string]
};
[storeViewController loadProductWithParameters:parameters completionBlock:^(BOOL result, NSError *error) {

if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[currentVc presentViewController:storeViewController animated:YES completion:^{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AppUpdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}];
});
}else{
NSLog(@"%@",error);
}
}];

}else{
NSString *appStroeStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/cn/app/id%@?l=en&mt=8", APPID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStroeStr]];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AppUpdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];

使用runtime,获取调出的appStore界面后点击取消button时的方法,用于dismiss自己,写了一个SKStoreProductViewController的扩展类

+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = NSSelectorFromString(@"_didFinish"); //动态获取当前控制器点击取消时候的方法,以便dismiss自己
SEL swizzledSelector = @selector(vc_didFinish);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, me
3ff7
thod_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}

在自定义的方法里边调用,dismiss

- (void)vc_didFinish{
[self vc_didFinish];
[self dismissViewControllerAnimated:YES completion:nil];
}

其中,用了递归算法,用于获取alertVc里边用于展示message的Label,使它的文字对中方式为距左对齐

/**
递归算法
*/
+ (UIView *)getParentViewOfTitleAndMessageFromView:(UIView *)view {
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
return view;
}else{
UIView *resultV = [self getParentViewOfTitleAndMessageFromView:subView];
if (resultV) return resultV;
}
}
return nil;
}
/**
富文本编辑

@param string 要编辑的字符串
@param range 需要改变的字符串range
@param color 字体颜色
@param font 字体大小
@return 修改后的字符串
*/
+ (NSMutableAttributedString *)changeStrWith:(NSString *)string
range:(NSRange)range
strColor:(UIColor *)color
strFont:(UIFont *)font
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
[attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
[attributedString addAttribute:NSFontAttributeName value:font range:range];
return attributedString;
}

获取当前系统展示的控制器,用于模态alertVc跟SKStoreProductViewController

/**
获取当前显示的控制器

@return 当前控制器
*/
+ (UIViewController *)activityViewController
{
UIViewController* activityViewController = nil;

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
if(window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow *tmpWin in windows)
{
if(tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
NSArray *viewsArray = [window subviews];
if([viewsArray count] > 0)
{
UIView *frontView = [viewsArray objectAtIndex:0];

id nextResponder = [frontView nextResponder];

if([nextResponder isKindOfClass:[UIViewController class]])
{
activityViewController = nextResponder;
}
else
{
activityViewController = window.rootViewController;
}
}

return activityViewController;
}

具体的代码实现,请前往gitHub下载源码参照,如果有什么问题欢迎留言探讨。
下载地址

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: