iOS不添加任何信息檢測App更新

一.前言:

  • 1.iOS開發中,有時會有這種需求,在AppStore上出現新版本時,應用內彈窗提示用戶更新.
  • 2.之前在網上看到一種方法通過AppId查詢更新的,但是有時候APP沒上線或開發賬號還沒注冊下來時我們并不知道AppId,此時就要把這個功能做上去,該怎么辦呢?
  • 3.現介紹一種簡便的方法給大家,不需要提供AppId等任何信息,即可實現查詢AppStore中是否有新版本,并提示更新.
  • 4.代碼地址:見篇尾.

二.效果:

效果.png

三.實現邏輯:

  • 1.先查詢AppStore中該App的信息(包含版本,更新日志等)
  • 2.和App當前版本進行比較,比當前版本新,彈窗并顯示更新日志,提示用戶跳轉到AppStore更新
  • 3.為了方便在以后開發中調用,筆者實現時進行簡單封裝.

四.直接上代碼:

-4.1獲取AppStore中該App的版本信息

  • 1.為了不依賴其他數據請求庫,筆者采用系統方法做數據請求,當然你們也可以使用AFN等框架請求數據.
  • 2.新建一個請求版本信息的類繼承NSObject筆者取名 XHVersionRequest
  • 3.在XHVersionRequest.h文件中添加請求成功和失敗回調和數據請求方法,代碼如下:

#import <Foundation/Foundation.h>

typedef void(^RequestSucess) (NSDictionary * responseDict);
typedef void(^RequestFailure) (NSError *error);

@interface XHVersionRequest : NSObject

/**
 *  從AppStore中獲取App信息
 *
 *  @param success 成功回調
 *  @param failure 失敗回調
 */
+(void)xh_versionRequestSuccess:(RequestSucess)success failure:(RequestFailure)failure;

@end

  • 4.在XHVersionRequest.m文件中實現

#import "XHVersionRequest.h"

@implementation XHVersionRequest
+(void)xh_versionRequestSuccess:(RequestSucess)success failure:(RequestFailure)failure{
    
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *bundleId = infoDict[@"CFBundleIdentifier"];
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@",bundleId]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if(!error)
                {
                    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: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 <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface XHAppInfo : 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"

@implementation XHAppInfo

- (instancetype)initWithResult:(NSDictionary *)result{
    
    self = [super init];
    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"];
    }
    return self;
}
@end

-4.3比較與當前版本大小關系,提示更新

  • 1.筆者新建一個類XHVersion(繼承NSObject)來處理版本比較和彈窗

  • 2.為了調用更靈活,我們在XHVersion.h文件中添加如下兩個方法:1.一個是使用默認彈窗,2.一個是回調新版本信息,開發者自定義彈窗

  • XHVersion.h文件

#import <Foundation/Foundation.h>
#import "XHAppInfo.h"

typedef void(^NewVersionBlock)(XHAppInfo *appInfo);

@interface XHVersion : NSObject

/**
 *  檢測新版本(使用默認提示框)
 */
+(void)checkNewVersion;

/**
 *  檢測新版本(自定義提示框)
 *
 *  @param newVersion 新版本信息回調
 */
+(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion;

@end

  • XHVersion.m文件中進行實現,代碼如下

#import "XHVersion.h"
#import "XHVersionRequest.h"

@interface XHVersion()<UIAlertViewDelegate>

@property(nonatomic,strong)XHAppInfo *appInfo;

@end

@implementation XHVersion

+(void)checkNewVersion{
    
    [[XHVersion shardManger] checkNewVersion];
}
+(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion{
    
    [[XHVersion shardManger] checkNewVersionAndCustomAlert:newVersion];
}

#pragma mark - private

+(XHVersion *)shardManger{
    
    static XHVersion *instance = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken,^{
        
        instance = [[XHVersion alloc] init];
        
    });
    return instance;
}
-(void)checkNewVersion{
    
    [self versionRequest:^(XHAppInfo *appInfo) {
    
        NSString *updateMsg = [NSString stringWithFormat:@"%@",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_0
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"發現新版本" message:updateMsg preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"關閉" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            [self openInAppStoreForAppURL:self.appInfo.trackViewUrl];
            
        }]];
        
        [[self window].rootViewController presentViewController:alert animated:YES completion:nil];
#endif
        
    }];

}
-(UIWindow *)window{
    
    UIWindow *window = nil;
    id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate respondsToSelector:@selector(window)]) {
        window = [delegate performSelector:@selector(window)];
    } else {
        window = [[UIApplication sharedApplication] keyWindow];
    }
    return window;
}
-(void)checkNewVersionAndCustomAlert:(NewVersionBlock)newVersion{
    
    [self versionRequest:^(XHAppInfo *appInfo) {
        
        if(newVersion) newVersion(appInfo);
        
    }];
}
-(void)versionRequest:(NewVersionBlock)newVersion{
    
    [XHVersionRequest xh_versionRequestSuccess:^(NSDictionary *responseDict) {
        
        NSInteger resultCount = [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([self isNewVersion: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.如果你需要自定義提示框,請使用下面方法
     [XHVersion checkNewVersionAndCustomAlert:^(XHAppInfo *appInfo) {
        
        //appInfo為新版本在AppStore相關信息
        //請在此處自定義您的提示框
        //......
    }];

六.小結:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容