30.iPhone的电源传感器简单介绍
2015-12-27 17:12
369 查看
继续我们上一章的内容, 这次我们讲解的是电源传感器, 简单来讲就是电池的状态, 每当电池发生变化时, 就回去调用一下电源传感器, 比如充电, 耗电之类的.
PS: 已经更新到Swift 2.1, 支持iOS 9.1
项目工程: 链接: http://pan.baidu.com/s/1kTMuI03 密码: 3kqm
PS: 已经更新到Swift 2.1, 支持iOS 9.1
1.实现代码
[code]import UIKit import CoreMotion class ViewController: UIViewController { var cmm: CMMotionManager! override func viewDidLoad() { super.viewDidLoad() // 1.实例化CMMotionManager cmm = CMMotionManager() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { // 1.打开电源传感器 UIDevice.currentDevice().batteryMonitoringEnabled = true // 2.打印电池的电量, 1.0表示已经充满 println("电池电量 = \(UIDevice.currentDevice().batteryLevel)") // 3.添加一个通知, 每当电池一旦有变化, 就调用levelChanged方法 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("levelChanged"), name: UIDeviceBatteryLevelDidChangeNotification, object: nil) } // 4.关掉页面之后, 把通知删除 override func viewDidDisappear(animated: Bool) { // 4.1.这里我们对删除通知的名字做一个详细的处理, 这样子我们就可以不会在多通知的情况下把别的通知给删除. NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceBatteryLevelDidChangeNotification, object: nil) } // 5.自定义打印电池电量的方法 func levelChanged() { println("电池电量 = \(UIDevice.currentDevice().batteryLevel)") } }
2.最终效果
项目工程: 链接: http://pan.baidu.com/s/1kTMuI03 密码: 3kqm
相关文章推荐
- jfinal-utils
- [fMRI手册]Handbook of functional MRI Data Analysis—Chapter 5
- Openwrt编译问题:Libnettle 3.1 was not found.
- Java基础之数据类型
- 29.iPhone距离传感器的简单使用
- 【机器学习】Softmax Regression简介
- lab 1实验报告
- 字符编码简介
- 编译C51项目的bat脚本
- Objc 精选 - 3D Touch 之 Peek & Pop 操作
- asp.net项目页面间传值的几种方式(部分转载)
- UVa 1433 - Aerodynamics
- CSharpGL(8)使用3D纹理渲染体数据 (Volume Rendering) 初探
- LeetCode Find Minimum in Rotated Sorted Array
- 3D Touch详解
- smbpasswd
- Leetcode: Additive Number
- “初心”-2012年终总结
- android软件引导界面
- 删除 右键--使用windows Defender扫描