一、环境光传感器(Ambient Light Sensor)
二、距离传感器(Proximity Sensor)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//1.开启距离传感器
UIDevice.current.isProximityMonitoringEnabled = true;
//2.添加一个通知,监听是否有物体靠近
NotificationCenter.default.addObserver(self, selector: #selector(change), name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil)
}
@objc
func change() {
if UIDevice.current.proximityState {
print("有物体靠近")
}else{
print("有物体离开")
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
三、磁力计传感器(Magmetometer Sensor)
四、内部温度传感器
五、湿度传感器
六、陀螺仪
七、运动传感器
1、加速计
(1)iOS4.0以前
(2)iOS4.0以后
import UIKit
//导入CoreMotion
import CoreMotion
class ViewController: UIViewController {
var motionManager:CMMotionManager?
override func viewDidLoad() {
super.viewDidLoad()
//1.创建运动管理者
motionManager = CMMotionManager()
//1.0、设置更新频率
motionManager?.accelerometerUpdateInterval = 1.0/3.0
//1.1、判断能不能用
if !(motionManager?.isAccelerometerAvailable)! {
print("你的硬件坏了")
return
}
//2.开始检测
//2.1、拉(pull)
motionManager?.startAccelerometerUpdates()
//2.2、推(push):就是把数据主动推送给外界
// motionManager?.startAccelerometerUpdates(to: OperationQueue.main, withHandler: { (data, error) in
// print(data!.acceleration)
// })
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//若使用pull,直接获取数据
print(motionManager?.accelerometerData)
}
}
2、摇一摇
方法1:通过分析加速计数据来判断是否进行摇一摇操作(比较复杂)。
方法2:通过iOS自带的Shake 监控API(非常简单)。
import UIKit
class ViewController: UIViewController {
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
print("摇一摇开始")
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
print("摇一摇结束")
}
override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) {
print("摇一摇取消")
}
}
3、计步器
作用:1.可以判断走了多少步数 。2.判断当前楼层。
(1)8.0之前
import UIKit
import CoreMotion
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !CMStepCounter.isStepCountingAvailable(){
print("计步器不能使用")
return
}
//1.创建一个计步器对象
let stepCounter: CMStepCounter = CMStepCounter()
//2.开始计步
let start = NSDate(timeIntervalSinceNow: -24*60*60) as Date
let to = NSDate(timeIntervalSinceNow: 0) as Date
stepCounter.queryStepCountStarting(from: start, to: to, to: OperationQueue.main) { (count, error) in
print(count)
}
}
}
(2、)8.0之后
import UIKit
import CoreMotion
class ViewController: UIViewController {
var pedometer: CMPedometer?
override func viewDidLoad() {
super.viewDidLoad()
//判断计步器是否可用
if !CMPedometer.isStepCountingAvailable() {
print("计步器不可以用")
return
}
//2.创建计步器对象,开始计步
pedometer = CMPedometer()
let now = NSDate(timeIntervalSinceNow: 0) as Date
pedometer!.startUpdates(from: now) { (data: CMPedometerData?, error: Error?) in
// data?.numberOfSteps:步数
// data?.distance 距离
// data?.floorsAscended 上楼
// data?.floorsDescended 下楼
// data?.currentPace步幅
// data?.currentCadence步频
print(data)
}
}
}
网友评论