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相關信息
        //請在此處自定義您的提示框
        //......
    }];

六.小結:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,836評論 6 540
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,275評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,904評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,633評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,368評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,736評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,740評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,919評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,481評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,235評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,427評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,968評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,656評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,055評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,348評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,160評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,380評論 2 379

推薦閱讀更多精彩內容