iOS获取当前设备信息的UIDevice
iOS获取当前设备信息的UIDevice

iOS获取当前设备信息的UIDevice

UIDevice 类属于 UIKit 框架(需要 import UIKit) ,它为你提供获取当前设备信息的能力。这包括:

1、设备的具体模型(iPad 或者 iPhone)。

2、系统版本。

3、唯一标识(UUID)。

4、设备是不是模拟器。

单例模式

需要通过UIDevice提供的单例调用其属性:

import UIKit

let device = UIDevice.current
if device.userInterfaceIdiom == .phone {
    // 这是 iPhone
} else if device.userInterfaceIdiom == .pad {
    // 这是 iPad
}

通过调用UIDevice的单例获取userInterfaceIdiom属性,从而判断当前设备属于iPad还是iPhone。

主要属性

let device = UIDevice.current

// 1、设备的名称(由用户自己设置)
print("设备名稱: \(device.name)") // 例如 "Alice 的 iPhone"

// 2、设备的模型
print("设备模型: \(device.model)") // 可能是 "iPhone"、"iPad"

// 3、本地化模型
print("本地化模型: \(device.localizedModel)") 

// 4、系统
print("系统: \(device.systemName)") 

// 5、系统版本
print("操作系统版本: \(device.systemVersion)") // 例如 "16.0"

// 6、唯一标识 (每个 App 都不同)
print("唯一标识: \(device.identifierForVendor?.uuidString ?? "无")")

// 7、设备的种类
if device.userInterfaceIdiom == .phone {
    print("为iPhone")
} else if device.userInterfaceIdiom == .pad {
    print("为iPad")
}

// 8、电池信息
UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = UIDevice.current.batteryLevel // 0.0~1.0
let batteryState = UIDevice.current.batteryState // .unknown, .charging, .full, .unplugged

// 9、近接传感器
UIDevice.current.isProximityMonitoringEnabled = true
let isProximity = UIDevice.current.proximityState // 有无遮挡

//  10、检测横屏和竖屏
print("检测横屏: \(device.orientation.isLandscape)") // 例如 "true"
print("检测竖屏: \(device.orientation.isPortrait)") // 例如 "false"
// 注意:有时 UIDevice 可能不会立即发生 refresh,需要搭配 UIDevice.beginGeneratingDeviceOrientationNotifications() 才能获取到。

// UIDevice生产出的通知进行订阅
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(
    forName: UIDevice.orientationDidChangeNotification,
    object: nil,
    queue: .main
) { notification in
    // 处理横竖屏发生的改变
}

如果不进行订阅,用于横竖屏检测的UIDevice.current.orientation可能一直无效。

总结

UIDevice提供:

1、设备模型

2、系统版本

3、唯一标识

4、用户为该设备设置的名称

5、甚至可以用它进行 UI 适配

在使用的过程中,需要通过 UIDevice.current 单例进行访问。

需要注意:UIDevice主要提供整体信息,若需要获取比如电池信息、内存甚至CPU信息,需要借用其他API。

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注