摇一摇
先说一个简单的
直接在你的appdelegate.m调用以下三个方法
/**
* 开始摇晃时调用
*
* @param motion 摇晃事件类型
* @param event 事件
*/
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@”%s”,func);
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@”%s”,func);
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@”%s”,func);
}
恭喜你, 你已经实现了摇一摇了
是不是很简单啊
距离传感器
建一个ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
/**
* 添加距离传感器检测
*/
[self addDistanceSensor];
}
-(void)addDistanceSensor
{
[[UIDevice currentDevice]setProximityMonitoringEnabled:YES];
// 1.通知 可在子线程或者主线程执行
[[NSNotificationCenter defaultCenter]addObserverForName:UIDeviceProximityStateDidChangeNotification object:nil queue:[[NSOperationQueue alloc]init] usingBlock:^(NSNotification *note) {
NSLog(@"%@",[NSThread currentThread]);
if ([[UIDevice currentDevice] proximityState])
{
// [self.centerButton setTitle:@”有人接近” forState:UIControlStateNormal];
NSLog(@"有人接近了");
}else
{
[self.centerButton setTitle:@"有人接近过" forState:UIControlStateNormal];
}
}];
//.2 原来的通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(note) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
-(void)note
{
if ([[UIDevice currentDevice] proximityState])
{
// [self.centerButton setTitle:@"有人接近" forState:UIControlStateNormal];
NSLog(@"有人接近了");
}else
{
[self.centerButton setTitle:@"有人接近过" forState:UIControlStateNormal];
}
}
-(void)dealloc
{
warning !!!!—通知必须在dealloc处移除
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
现在实现了打电话屏幕变黑的功能
加速传感器
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib./**
- 添加加速计传感器检测
*/
[self addAccelerationSensorByUIAccelerometer];
[self addAccelerationSensorByCoreMotion];
[self addAccelerationSensorByCoreMotionUsingPull];
- 添加加速计传感器检测
}
-(void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
{
CMAccelerometerData *accelerometerData = self.mgr.accelerometerData;
NSLog(@"%f----%f",accelerometerData.acceleration.x,accelerometerData.acceleration.y);
}
pragma mark 加速器
// 1.UIAccelerometer
-(void)addAccelerationSensorByUIAccelerometer
{
UIAccelerometer *alt = [UIAccelerometer sharedAccelerometer];
alt.delegate = self;
alt.updateInterval = 1.0f;
}
-(void)accelerometer:(UIAccelerometer )accelerometer didAccelerate:(UIAcceleration )acceleration
{
NSLog(@”x:%f—y:%f—z:%f”,acceleration.x,acceleration.y,acceleration.z);
}
// 1.CoreMotion
-(void)addAccelerationSensorByCoreMotion
{
self.mgr = [[CMMotionManager alloc]init];
if (self.mgr.isMagnetometerAvailable)
{
self.mgr.accelerometerUpdateInterval = 1.0f;
[self.mgr startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
NSLog(@"%f----%f",accelerometerData.acceleration.x,accelerometerData.acceleration.y);
}];
}else
{
NSLog(@"不可用");
}
}
-(void)clickButton:(UIButton *)sender
{
// [self.mgr stopMagnetometerUpdates];
self.mgr = nil;
// [self.mgr stopMagnetometerUpdates];
}
-(void)addAccelerationSensorByCoreMotionUsingPull
{
self.mgr = [[CMMotionManager alloc]init];
if (self.mgr.isMagnetometerAvailable)
{
[self.mgr startAccelerometerUpdates];
}else
{
NSLog(@"不可用");
}
}
@end
磁力计
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//共5个步骤
//1 首先初始化一个地位管理器
self.locaManager =[[CLLocationManager alloc]init];
self.locaManager.delegate = self;//设置图片的位置
self.myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(80, 200, 200, 200)];
// self.myImageView.contentMode = UIViewContentModeCenter;
self.myImageView.image = [UIImage imageNamed:@”zhinanzhen2”];
[self.view addSubview:self.myImageView];//创建lable 放置手机与正北方向的夹角
self.myLable = [[UILabel alloc]initWithFrame:CGRectMake(80, 420, 200, 60)];
self.myLable.backgroundColor =[UIColor orangeColor];
self.myLable.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.myLable];UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(115, 100, 140, 60);
// button.frame = CGRectMake(100, 10, 100, 40);
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonClick) forControlEvents:(UIControlEventTouchUpInside)];
[button setTitle:@”打开设备磁力计” forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor yellowColor];//检测是否启用位置服务功能
if ([CLLocationManager locationServicesEnabled]) {
NSLog(@”locationServices isEnable”);//2 设置精度(越精确就越耗电) self.locaManager.desiredAccuracy = kCLLocationAccuracyBest; // 3.设置距离筛选器(每隔多少米定位一次) self.locaManager.distanceFilter = 100.0f; // 4.启动 位置管理器进行定位[locationManagerstartUpdatingLocation]; 如果我们不需要继续轮询更新位置可以使用[locationManager stopUpdatingLocation];停止更新,否则应用程序打开会一直更新,这些都需要添加委托的,遵循CLLocationManagerDelegate协议 [self.locaManager startUpdatingHeading];
}else
{
NSLog(@”定位服务不可用”);
}
}(void)buttonClick
{
//判断设备上的磁力计是否可以使用
if ([CLLocationManager headingAvailable]){
//headingAvailable该设备是否支持磁力计计算方向
[self.locaManager startUpdatingHeading];
}else{
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@”警告” message:@”没有查找到磁力计设备” preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@”确认” style:UIAlertActionStyleDefault handler:nil];
[alertC addAction:alertAction];
[self presentViewController:alertC animated:YES completion:nil];}
}
//当调用了startUpdatingHeading方法后,就开始不断地定位用户的位置,中途会频繁地调用下面的代理方法,这里定位出的结果是用户与真实北方的夹角
- (void)locationManager:(CLLocationManager )manager didUpdateHeading:(CLHeading )newHeading//CLHeading:该对象设备的移动方向
{
//将角度值转化为弧度制
CGFloat heading = -1.0f * M_PI * newHeading.magneticHeading / 180.0f;
//手机方向与真实北方(磁头方向)的夹角
self.myLable.text=[[NSString alloc]initWithFormat:@"手机正方向与正北夹角:%.2f",newHeading.magneticHeading];
//视图的旋转属性
//图片的方向与真实的北方一致
//CGAffineTranFormMakeRotation需要一个弧度制的参数 实现图片的旋转
[UIView animateWithDuration:1 animations:^{
self.myImageView.transform = CGAffineTransformMakeRotation(heading);
} completion:^(BOOL finished) {
NSLog(@"动画结束");
}];
}
//协议方法:定位用户信息出现错误时执行以下方法
- (void)locationManager:(CLLocationManager )manager didFailWithError:(NSError )error
{
NSLog(@”error”);
}
// 5. 最后一步不要忘记关掉传感器数据的更新
- (void)viewWillDisappear:(BOOL)animated{
if ([CLLocationManager locationServicesEnabled]) {
// [self.locationManager stopUpdatingLocation];
[self.locaManager stopUpdatingHeading];
}
}