專案中常常需要取得手機的相關資訊,讓使用者了解自己目前的環境與 App 版本,以下直接上程式碼。
應用程式的名稱、版本等資訊都存在 mainBundle 回傳的那個字典裡,用下面的方式就能取出:
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary]; NSString *versionNum = [infoDict objectForKey:@"CFBundleVersion"]; NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"]; NSString *text = [NSString stringWithFormat:@"%@ %@", appName, versionNum];
// 裝置類型 NSString *strModel = [UIDevice currentDevice].model; NSLog(@"%@", strModel); // 手機別名:使用者自訂的名稱 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]; // 當前應用名稱 NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"]; NSLog(@"當前應用名稱:%@", appCurName); // 當前應用軟體版本,例如 1.0.1 NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; NSLog(@"當前應用軟體版本:%@", appCurVersion); // 當前應用版本號碼 NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"]; NSLog(@"當前應用版本號碼:%@", appCurVersionNum);
CFBundleShortVersionString 與 CFBundleVersion 經常被搞混,兩者用途完全不同。前者是給使用者看的版本標記(如 1.0.1),每次對外發布時遞增;後者是建置編號,必須在每次上傳到 App Store 時遞增,即使對外顯示的版本沒變也一樣。要用來判斷「是不是新版本、需要強制更新」時,該比對的是前者。
另外,[UIDevice currentDevice].model 回傳的是「iPhone」這種通用品類,而 systemVersion 才是 7.1、8.0 這類系統版本。若需要精確到 iPhone 6、iPad Air 這種實機型號,model 是不夠的,得改用 uname() 讀取 utsname.machine 再自行對照。
最後提醒隱私面的考量:[UIDevice currentDevice].identifierForVendor 曾是常見的裝置識別方式,但自 iOS 7 起 Apple 已明令禁止取得 uniqueIdentifier,審核會被退回。若要追蹤使用行為,請改用 IDFA 或 IDFV,並在 App 內提供說明與重置選項。