做資料統計、回報 bug、引導使用者升級時,常需要知道「這是什麼機器、跑什麼系統、裝的是哪一版 App」。這些資訊分散在 UIDevice 與 NSBundle 兩個地方,整理一次之後就能重複使用。
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 或自行處理廣告識別碼。
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"];
[[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"] ?: @""
};
}
這樣在需要回報環境資訊、或做「最低支援版本」判斷時,一行就能拿到整包資料。