您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 小技巧:一次取得設備型號、系統版本與 App 版本資訊

編輯:iOS 開發綜合

做資料統計、回報 bug、引導使用者升級時,常需要知道「這是什麼機器、跑什麼系統、裝的是哪一版 App」。這些資訊分散在 UIDevice 與 NSBundle 兩個地方,整理一次之後就能重複使用。

從 UIDevice 取得硬體與系統資訊

NSLog(@"name: %@", [[UIDevice currentDevice] name]);              // 使用者自訂的裝置名稱
NSLog(@"systemName: %@", [[UIDevice currentDevice] systemName]);  // 例如 iPhone OS
NSLog(@"systemVersion: %@", [[UIDevice currentDevice] systemVersion]); // 例如 9.3.2
NSLog(@"model: %@", [[UIDevice currentDevice] model]);            // 例如 iPhone
NSLog(@"localizedModel: %@", [[UIDevice currentDevice] localizedModel]);

要注意的是,uniqueIdentifier(UDID)自 iOS 5 起已被蘋果移除,正式取用會拿到 nil 甚至無法通過審核,請改用 identifierForVendor 或自行處理廣告識別碼。

從 mainBundle 的 infoDictionary 取得 App 資訊

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
CFShow(infoDictionary);

// App 顯示名稱
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];

// App 版本(給使用者看的版本號,例如 1.2.0)
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

// App build 版本(同一版本號下的建置序號,用於判定升級)
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];

實務上的兩個提醒

model 只會告訴你「iPhone」,不是「iPhone 5s」

[[UIDevice currentDevice] model] 回傳的是家族名稱,例如 iPhone、iPad。若需要精確機型,得走另一條路,這部分可參考後續關於 uname 與 machine 識別碼的說明。

版本比較不要直接用字串比大小

CFBundleShortVersionString 是字串,「1.10.0」在字典序下反而小於「1.9.0」。要比較版本,請轉成數字或串接成可比較的格式:

NSString *current = app_Version;
NSString *latest  = @"1.10.0";

// 方法一:逐段轉整數組裝成可比較的整數
NSArray *a = [current componentsSeparatedByString:@"."];
NSArray *b = [latest  componentsSeparatedByString:@"."];

// 方法二:直接用 NSNumericSearch 讓系統以數字語意比較
NSComparisonResult result = [current compare:latest options:NSNumericSearch];
if (result == NSOrderedAscending) {
    NSLog(@"有新版本可以更新");
}

包成一個方便的工具方法

+ (NSDictionary *)deviceInfo {
    NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
    UIDevice *device = [UIDevice currentDevice];
    return @{
        @"model"        : [device model],
        @"systemName"   : [device systemName],
        @"systemVersion": [device systemVersion],
        @"appName"      : [info objectForKey:@"CFBundleDisplayName"] ?: @"",
        @"appVersion"   : [info objectForKey:@"CFBundleShortVersionString"] ?: @"",
        @"appBuild"     : [info objectForKey:@"CFBundleVersion"] ?: @""
    };
}

這樣在需要回報環境資訊、或做「最低支援版本」判斷時,一行就能拿到整包資料。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved