小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
在iOS开发中,我们不可避免要和硬件设备的参数打交道。
比如举几个最简单的例子,判断是iPhone还是iPad,是刘海屏还是一般屏幕等等。
虽然每个App针对自身情况,会根据自己的业务场景去编写相关的逻辑,去兼容、去适配这些硬件。
那么有没有一个库,能够完美的解决涉及设备硬件的判断与业务呢?
今天给大家介绍的这个DeviceKit
就能解决这个问题。
DeviceKit
DeviceKit是一个使用Swift编写的涉及Apple设备硬件的开源库。
它可以有多种集成方式——Cocopods、Swift Package Manager、Carthage、Manually。
它可以判断各种设备机型(包括模拟器)、获取电池电量、是否在省电模式、屏幕亮度、硬盘空间等等一系列功能。
引用官方的简介,我们可以感受到它的魅力:
DeviceKit is a value-type replacement of UIDevice.
我个人觉得DeviceKit的优点就在于:将那些硬编码的字符串,出色的整理成为了枚举类型。让在函数调用变得极度舒适,容易书写并处理。
看看官方的例子你就会感受到它的安全性和简洁性:
import DeviceKit
import UIKit
let device = Device()
print(device) // prints, for example, "iPhone 6 Plus"
/// Get the Device You're Running On
if device == .iPhone6Plus {
// Do something
} else {
// Do something else
}
/// Get the Device Family
if device.isPod {
// iPods (real or simulator)
} else if device.isPhone {
// iPhone (real or simulator)
} else if device.isPad {
// iPad (real or simulator)
}
/// Check If Running on Simulator
if device.isSimulator {
// Running on one of the simulators(iPod/iPhone/iPad)
// Skip doing something irrelevant for Simulator
}
/// Get the Simulator Device
switch device {
case .simulator(.iPhone6s): break // You're running on the iPhone 6s simulator
case .simulator(.iPadAir2): break // You're running on the iPad Air 2 simulator
default: break
}
/// Make Sure the Device Is Contained in a Preconfigured Group
let groupOfAllowedDevices: [Device] = [.iPhone6,
.iPhone6Plus,
.iPhone6s,
.iPhone6sPlus,
.simulator(.iPhone6),
.simulator(.iPhone6Plus),
.simulator(.iPhone6s),
.simulator(.iPhone6sPlus)]
if device.isOneOf(groupOfAllowedDevices) {
// Do your action
}
而DeviceKit
的源码,仅仅只有一个文件,不到2000行代码。
大家有兴趣的可以去看看这个源码,其实没有太多的技术含量,但是对于代码的格式和风格,我觉得都是值得借鉴与学习的。
它能判断的不仅是iOS系列的硬件喔,如果注意看会发现更多内容。^_^
参考文档
DeviceKitPlayground.playground
总结
DeviceKit
短小精悍,却不失优美。将它集成到工程中,占用不了太多的资源,但是我想它会对你的开发起到作用的。
我们下期见。