時間?2016-11-23 09:35:54CocoaChina
原文http://www.cocoachina.com/ios/20161123/18170.html
主題iOS開發
一.前言:
1.iOS開發中,有時會有這種需求,在AppStore上出現新版本時,應用內彈窗提示用戶更新.
2.之前在網上看到一種方法通過AppId查詢更新的,但是有時候APP沒上線或開發賬號還沒注冊下來時我們并不知道AppId,此時就要把這個功能做上去,該怎么辦呢?
3.現介紹一種簡便的方法給大家,不需要提供AppId等任何信息,即可實現查詢AppStore中是否有新版本,并提示更新.
4.代碼地址:見篇尾.
二.效果:
三.實現邏輯:
1.先查詢AppStore中該App的信息(包含版本,更新日志等)
2.和App當前版本進行比較,比當前版本新,彈窗并顯示更新日志,提示用戶跳轉到AppStore更新
3.為了方便在以后開發中調用,筆者實現時進行簡單封裝.
四.直接上代碼:
-4.1獲取AppStore中該App的版本信息
1.為了不依賴其他數據請求庫,筆者采用系統方法做數據請求,當然你們也可以使用AFN等框架請求數據.
2.新建一個請求版本信息的類繼承NSObject筆者取名 XHVersionRequest
3.在XHVersionRequest.h文件中添加請求成功和失敗回調和數據請求方法,代碼如下:
#importtypedefvoid(^RequestSucess) (NSDictionary * responseDict);typedefvoid(^RequestFailure) (NSError *error);@interfaceXHVersionRequest:NSObject/**
*? 從AppStore中獲取App信息
*
*? @param success 成功回調
*? @param failure 失敗回調
*/+(void)xh_versionRequestSuccess:(RequestSucess)successfailure:(RequestFailure)failure;@end
4.在XHVersionRequest.m文件中實現
#import"XHVersionRequest.h"@implementationXHVersionRequest+(void)xh_versionRequestSuccess:(RequestSucess)success failure:(RequestFailure)failure{NSDictionary*infoDict = [[NSBundlemainBundle] infoDictionary];NSString*bundleId = infoDict[@"CFBundleIdentifier"];NSURL*URL = [NSURLURLWithString:[NSStringstringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@",bundleId]];dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{NSURLRequest*request = [NSURLRequestrequestWithURL:URL];NSURLSessionDataTask*dataTask = [[NSURLSessionsharedSession] dataTaskWithRequest:request completionHandler:^(NSData* _Nullable data,NSURLResponse* _Nullable response,NSError* _Nullable error) {dispatch_async(dispatch_get_main_queue(), ^{if(!error)? ? ? ? ? ? ? ? {NSDictionary*responseDict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableLeaveserror:nil];if(success) success(responseDict);? ? ? ? ? ? ? ? }else{if(failure) failure(error);? ? ? ? ? ? ? ? }? ? ? ? ? ? });? ? ? ? }];? ? ? ? [dataTask resume];? ? });}@end
-4.2解析請求回來App信息數據
1.新建一個App信息模型繼承NSObject,筆者取名XHAppInfo,為減少依賴,筆者暫不采用JSON -> Model 框架解析數據.
2.在XHAppInfo.h和XHAppInfo.m中分別添加以下代碼:
XHAppInfo.h文件
#import#import@interfaceXHAppInfo : NSObject/** *? 版本號 */@property(nonatomic,copy) NSString * version;/**
*? 更新日志
*/@property(nonatomic,copy)NSString*releaseNotes;/**
*? 更新時間
*/@property(nonatomic,copy)NSString*currentVersionReleaseDate;/**
*? APPId
*/@property(nonatomic,copy)NSString*trackId;/**
*? bundleId
*/@property(nonatomic,copy)NSString*bundleId;/**
*? AppStore地址
*/@property(nonatomic,copy)NSString*trackViewUrl;-(instancetype)initWithResult:(NSDictionary*)result;@end
XHAppInfo.m文件
#import"XHAppInfo.h"@implementationXHAppInfo- (instancetype)initWithResult:(NSDictionary*)result{self= [superinit];if(self) {self.version = result[@"version"];self.releaseNotes = result[@"releaseNotes"];self.currentVersionReleaseDate = result[@"currentVersionReleaseDate"];self.trackId = result[@"trackId"];self.bundleId = result[@"bundleId"];self.trackViewUrl = result[@"trackViewUrl"];self.appDescription = result[@"appDescription"];self.sellerName = result[@"sellerName"];self.fileSizeBytes = result[@"fileSizeBytes"];self.screenshotUrls = result[@"screenshotUrls"];? ? }returnself;}@end
-4.3比較與當前版本大小關系,提示更新
1.筆者新建一個類XHVersion(繼承NSObject)來處理版本比較和彈窗
2.為了調用更靈活,我們在XHVersion.h文件中添加如下兩個方法:1.一個是使用默認彈窗,2.一個是回調新版本信息,開發者自定義彈窗
XHVersion.h文件
#import#import"XHAppInfo.h"typedefvoid(^NewVersionBlock)(XHAppInfo *appInfo);@interfaceXHVersion : NSObject/**
*? 檢測新版本(使用默認提示框)
*/+(void)checkNewVersion;/**
*? 檢測新版本(自定義提示框)
*
*? @param newVersion 新版本信息回調
*/+(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion;@end
XHVersion.m文件中進行實現,代碼如下
#import"XHVersion.h"#import"XHVersionRequest.h"@interfaceXHVersion()@property(nonatomic,strong)XHAppInfo*appInfo;@end@implementationXHVersion+(void)checkNewVersion{? ? [[XHVersion shardManger] checkNewVersion];}+(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion{? ? [[XHVersion shardManger] checkNewVersionAndCustomAlert:newVersion];}#pragma mark - private+(XHVersion *)shardManger{staticXHVersion *instance =nil;staticdispatch_once_toneToken;dispatch_once(&oneToken,^{? ? ? ? instance = [[XHVersion alloc] init];? ? });returninstance;}-(void)checkNewVersion{? ? [selfversionRequest:^(XHAppInfo *appInfo) {NSString*updateMsg = [NSStringstringWithFormat:@"%@",appInfo.releaseNotes];#if __IPHONE_OS_VERSION_MIN_REQUIRED< __IPHONE_8_0
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"發現新版本" message:updateMsg delegate:self cancelButtonTitle:@"關閉" otherButtonTitles:@"更新", nil];
[alertView show];
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"發現新版本"message:updateMsg preferredStyle:UIAlertControllerStyleAlert];? ? ? ? [alert addAction:[UIAlertActionactionWithTitle:@"關閉"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction* _Nonnull action) {? ? ? ? }]];? ? ? ? [alert addAction:[UIAlertActionactionWithTitle:@"更新"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction* _Nonnull action) {? ? ? ? ? ? [selfopenInAppStoreForAppURL:self.appInfo.trackViewUrl];? ? ? ? }]];? ? ? ? [[selfwindow].rootViewController presentViewController:alert animated:YEScompletion:nil];#endif}];}-(UIWindow*)window{UIWindow*window =nil;iddelegate = [[UIApplicationsharedApplication] delegate];if([delegate respondsToSelector:@selector(window)]) {? ? ? ? window = [delegate performSelector:@selector(window)];? ? }else{? ? ? ? window = [[UIApplicationsharedApplication] keyWindow];? ? }returnwindow;}-(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion{? ? [selfversionRequest:^(XHAppInfo *appInfo) {if(newVersion) newVersion(appInfo);? ? }];}-(void)versionRequest:(NewVersionBlock)newVersion{? ? [XHVersionRequest xh_versionRequestSuccess:^(NSDictionary*responseDict) {NSIntegerresultCount = [responseDict[@"resultCount"] integerValue];if(resultCount==1)? ? ? ? {NSArray*resultArray = responseDict[@"results"];NSDictionary*result = resultArray.firstObject;? ? ? ? ? ? XHAppInfo *appInfo = [[XHAppInfo alloc] initWithResult:result];NSString*version = appInfo.version;self.appInfo = appInfo;if([selfisNewVersion:version])//新版本{if(newVersion) newVersion(self.appInfo);? ? ? ? ? ? }? ? ? ? }? ? } failure:^(NSError*error) {? ? }];}#if __IPHONE_OS_VERSION_MIN_REQUIRED< __IPHONE_8_0
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex==1)
{
[self openInAppStoreForAppURL:self.appInfo.trackViewUrl];
}
}
#endif
-(void)openInAppStoreForAppURL:(NSString *)appURL{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appURL]];
}
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
[viewController dismissViewControllerAnimated:YES completion:nil];
}
//是否是新版本
-(BOOL)isNewVersion:(NSString *)newVersion{
return [self newVersion:newVersion moreThanCurrentVersion:[self currentVersion]];
}
-(NSString * )currentVersion{
NSString *key = @"CFBundleShortVersionString";
NSString * currentVersion = [NSBundle mainBundle].infoDictionary[key];
return currentVersion;
}
-(BOOL)newVersion:(NSString *)newVersion moreThanCurrentVersion:(NSString *)currentVersion{
if([currentVersion compare:newVersion options:NSNumericSearch]==NSOrderedAscending)
{
return YES;
}
return NO;
}
五.調用:
導入頭文件 #import "XHVersion.h" ,在需要檢測新版本的地方調用下面代碼
//1.新版本檢測(使用默認提示框)[XHVersion checkNewVersion];//2.如果你需要自定義提示框,請使用下面方法[XHVersioncheckNewVersionAndCustomAlert:^(XHAppInfo *appInfo) {//appInfo為新版本在AppStore相關信息//請在此處自定義您的提示框//......}];
六.小結:
細看代碼的同學可能會發現,筆者并沒有通過AppId去拉取該App的版本信息,而是通過bundleId去查詢的.