继续我们上一章的内容, 这次我们讲解的是电源传感器, 简单来讲就是电池的状态, 每当电池发生变化时, 就回去调用一下电源传感器, 比如充电, 耗电之类的.
PS: 已经更新到Swift 2.1, 支持iOS 9.1
1.实现代码
import UIKit
import CoreMotion
class ViewController: UIViewController {
var cmm: CMMotionManager!
override func viewDidLoad() {
super.viewDidLoad()
cmm = CMMotionManager()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
UIDevice.currentDevice().batteryMonitoringEnabled = true
println("电池电量 = (UIDevice.currentDevice().batteryLevel)")
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("levelChanged"), name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
}
func levelChanged() {
println("电池电量 = (UIDevice.currentDevice().batteryLevel)")
}
}
2.最终效果
项目工程: 链接:
http://pan.baidu.com/s/1kTMuI03 密码: 3kqm