前言
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIDevice : NSObject
@available(iOS 2.0, *) public class UIDevice : NSObject
iOS 的 APP 应用开发的过程中,有时为了 bug 跟踪或者获取用反馈的需要自动收集用户设备、系统信息、应用信息等等,这些信息方便开发者诊断问题,当然这些信息是用户的非隐私信息,是通过开发 api 可以获取到的。那么通过那些 api 可以获取这些信息呢,iOS 的 SDK 中提供了 UIDevice,NSBundle,NSLocale。
UIDevice 提供了多种属性、类函数及状态通知,帮助我们全方位了解设备状况。从检测电池电量到定位设备与临近感应,UIDevice 所做的工作就是为应用程序提供用户及设备的一些信息。UIDevice 类还能够收集关于设备的各种具体细节,例如机型及 iOS 版本等。其中大部分属性都对开发工作具有积极的辅助作用。
bundle 是一个目录,其中包含了程序会使用到的资源。这些资源包含了如图像、声音、编译好的代码、nib 文件(用户也会把 bundle 称为 plug-in),对应 bundle,cocoa 提供了类 NSBundle。一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了 nib 文件,编译代码,以及其他资源的目录。我们把这个目录叫做程序的 main bundle。通过这个路径可以获取到应用的信息,例如应用名、版本号等。
NSLocale 可以获取用户的本地化信息设置,例如货币类型,国家,语言,数字,日期格式的格式化,提供正确的地理位置显示等等。下面的代码获取机器当前语言和国家代码。
1、设备相关信息的获取
Objective-C
设备基本信息
// 获取当前设备 UIDevice *device = [UIDevice currentDevice]; // 获取设备名称 /* e.g. "My iPhone" */ NSString *name = device.name; // 获取设备类型 /* e.g. @"iPhone", @"iPod touch" */ NSString *model = device.model; // 获取本地化设备类型 /* localized version of model */ NSString *localizedModel = device.localizedModel; // 获取设备系统名称 /* e.g. @"iOS" */ NSString *systemName = device.systemName; // 获取设备系统版本 /* e.g. @"4.0" */ NSString *systemVersion = device.systemVersion; // 获取设备 UUID /* 可用于唯一标识该设备,同一供应商不同应用具有相同的 UUID */ NSUUID *identifierForVendor = device.identifierForVendor; NSString *UUID = identifierForVendor.UUIDString;
设备方向
// 判断设备是否生成设备转向通知 BOOL generatesDeviceOrientationNotifications = device.isGeneratingDeviceOrientationNotifications; // 开启设备转向通知 /* 通过调用该方法通知设备:如果用户改变了设备的朝向,我们想获悉这一点 在注册设备方向通知时,需要先调用该方法 */ [device beginGeneratingDeviceOrientationNotifications]; // 停止设备转向通知 /* 在移除设备方向通知后,需要调用该方法 */ [device endGeneratingDeviceOrientationNotifications]; // 注册屏幕方向变化通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:@"UIDeviceOrientationDidChangeNotification" object:nil]; // 获取设备方向 /* UIDeviceOrientationUnknown, UIDeviceOrientationPortrait, // home button on the bottom 竖向,头向上 UIDeviceOrientationPortraitUpsideDown, // home button on the top 竖向,头向下 UIDeviceOrientationLandscapeLeft, // home button on the right 横向,头向左 UIDeviceOrientationLandscapeRight, // home button on the left 横向,头向右 UIDeviceOrientationFaceUp, // face up 平放,屏幕朝上 UIDeviceOrientationFaceDown // face down 平放,屏幕朝下 除非正在生成设备方向的通知,否则返回 UIDeviceOrientationUnknown */ UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
设备电池监控
// 判断设备是否开启电池监控 /* default is NO */ BOOL batteryMonitoringEnabled = device.isBatteryMonitoringEnabled; // 开启电池监控 /* default is NO */ device.batteryMonitoringEnabled = YES; // 获取设备电池状态 /* UIDeviceBatteryStateUnknown, UIDeviceBatteryStateUnplugged, // on battery, discharging 未充电 UIDeviceBatteryStateCharging, // plugged in, less than 100% 正在充电 UIDeviceBatteryStateFull, // plugged in, at 100% 满电 如果禁用电池监控,则电池状态为 UIDeviceBatteryStateUnknown */ UIDeviceBatteryS