做資料回報、客服資訊頁或隱私政策說明時,常需要顯示一堆環境資訊。這些多半能從 UIDevice 與 mainBundle 的 infoDictionary 取得。
// 裝置識別碼
NSString *identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString];
NSLog(@"裝置識別碼: %@", identifierNumber);
// 使用者自訂的別名
NSString *userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"手機別名: %@", userPhoneName);
// 系統名稱
NSString *deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"系統名稱: %@", deviceName);
// 系統版本
NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"系統版本: %@", phoneVersion);
// 裝置型號
NSString *phoneModel = [[UIDevice currentDevice] model];
NSLog(@"裝置型號: %@", phoneModel);
// 本地化機型名稱
NSString *localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"本地化名稱: %@", localPhoneModel);
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// App 顯示名稱
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"App 名稱:%@", appCurName);
// 版本字串,例如 1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"App 版本:%@", appCurVersion);
// 建置號碼
NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"App 建置號:%@", appCurVersionNum);
identifierForVendor 不是 IDFA,也不是永久識別碼。它代表「同一開發者的 App 在該裝置上的共同識別值」。若使用者把所有同開發者的 App 都移除,這個值就會改變;即使只移除其中一個,一段時間後也可能重新產生。因此它適合拿來做分析歸屬,但不能當作帳號的唯一鍵,那樣會在使用者重裝後對不上資料。
若需要廣告追蹤識別碼,要用 ASIdentifierManager 的 advertisingIdentifier,而且必須先處理 ATT 授權(App Tracking Transparency),使用者拒絕時該值會全為 0。
model 與 machine 是兩回事。[[UIDevice currentDevice] model] 只會回傳 iPhone/iPad 這種粗略類別;若要取得 iPhone15,2 這類硬體識別碼,得用 sysctlbyname("hw.machine"),這在需要依晶片型號做效能分級時才用得上。
至於序號(serial number)與 IMEI 這類資訊,自 iOS 7 起已被系統完全禁止存取,任何聲稱能取得的寫法都無法通過審核,實作時不要浪費時間嘗試。
最後,CFBundleShortVersionString 是給使用者看的版本(1.2.0),CFBundleVersion 是給系統判斷升級用的建置號,兩者用途不同,回報 bug 時建議兩個都附上,再加上系統版本與裝置型號,客服排查會順利很多。