一、加速度、陀螺仪、电源、距离传感器的使用方法:
import UIKit
import CoreMotion
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
var cmm:CMMotionManager!
var lm:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
cmm = CMMotionManager()
lm = CLLocationManager()
lm.delegate = self
}
func StartAccerometer(){
cmm.accelerometerUpdateInterval = 1
if cmm.accelerometerAvailable && !cmm.accelerometerActive{
cmm.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {(data:CMAccelerometerData?,err:NSError?) in
print("加速度数据:(data)")
})
}else{
print("加速度传感器不可用")
}
}
func StartGyrometer(){
cmm.gyroUpdateInterval = 1
if cmm.gyroAvailable && !cmm.gyroActive{
cmm.startGyroUpdatesToQueue(NSOperationQueue(), withHandler: {
(data:CMGyroData?,err:NSError?) in
print("陀螺仪数据:(data)")
})
}else{
print("陀螺仪传感器不可用") }
}
func Startproximitymeter(){
UIDevice.currentDevice().proximityMonitoringEnabled = true
NSNotificationCenter.defaultCenter().addObserver(self, selector:Selector("ProximityChanged"), name: UIDeviceProximityStateDidChangeNotification, object: nil)
}
func ProximityChanged(){
print("(UIDevice.currentDevice().proximityState)")
}
func StartListenBatteryLevel(){
UIDevice.currentDevice().batteryMonitoringEnabled = true
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("BatteryLevel"), name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
}
func BatteryLevel(){
UIDevice.currentDevice().batteryState
print("(UIDevice.currentDevice().batteryLevel)")
}
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
print(newHeading)
}
func StopBatteryLevel(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
}
func StopProximity(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceProximityStateDidChangeNotification, object: nil)
}
func StopAcceler(){
if cmm.accelerometerActive{
cmm.stopAccelerometerUpdates()
}
}
func StopGyro(){
if cmm.gyroActive {
cmm.stopGyroUpdates()
}
}
override func viewWillAppear(animated: Bool) {
StartAccerometer()
StartGyrometer()
Startproximitymeter()
StartListenBatteryLevel()
lm.startUpdatingHeading()
}
override func viewWillDisappear(animated: Bool) {
StopAcceler()
StopGyro()
StopProximity()
StopBatteryLevel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
二、磁场传感器的使用
import UIKit
import CoreLocation //磁场传感器的使用引入库:CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
var lm:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lm = CLLocationManager()
lm.delegate = self
}
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
p
rint(newHeading)
}
override func viewWillAppear(animated: Bool) {
lm.startUpdatingHeading()
}
不懂英文,学起来还是比较吃力的。又是英文基础良好的,学起来必定既轻松又好玩。