//联系人:石虎 QQ: 1224614774昵称:嗡嘛呢叭咪哄
/**
注意点: 1.看 GIF 效果图.
2.看连线视图的效果图.
3.看实现代码(直接复制实现效果).
4.需要真机设备 + 硬件设备 ...
*/
一、GIF 效果图:
二、连线视图的效果图:
图1:
图2:
三、实现代码:
=========================
===================================================
==========================控制器1:
//
// ViewController.m
// MotionManager(运动管理器)~demo
//
// Created by 石虎 on 2017/8/14.
// Copyright © 2017年 shihu. All rights reserved.
//
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>//核心运动框架
@interface ViewController ()
{
NSTimer *updateTimer;//更新时间
}
//运动管理器
@property (strong, nonatomic) CMMotionManager *motionManager;
//加速度计的标签
@property (strong, nonatomic) IBOutlet UILabel *accelerometerLabel;
//陀螺的标签
@property (strong, nonatomic) IBOutlet UILabel *gyroLabel;
//磁强计标签
@property (strong, nonatomic) IBOutlet UILabel *magnetometerLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建CMMotionManager对象
self.motionManager = [[CMMotionManager alloc] init];
// 如果CMMotionManager的支持获取加速度数据
if (self.motionManager.accelerometerAvailable)
{
[self.motionManager startAccelerometerUpdates];
}else{
NSLog(@"该设备不支持获取加速度数据!");
}
// 如果CMMotionManager的支持获取陀螺仪数据
if (self.motionManager.gyroAvailable)
{
[self.motionManager startGyroUpdates];
}else{
NSLog(@"该设备不支持获取陀螺仪数据!");
}
// 如果CMMotionManager的支持获取磁场数据
if (self.motionManager.magnetometerAvailable)
{
[self.motionManager startMagnetometerUpdates];
}else{
NSLog(@"该设备不支持获取磁场数据!");
}
}
#pragma mark - 视图将要显示的时候
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// 启动定时器来周期性地轮询加速度、陀螺仪、磁场数据
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self selector:@selector(updateDisplay)
userInfo:nil repeats:YES]; // ②
}
#pragma mark - 定时器回调
- (void)updateDisplay
{
// 如果CMMotionManager的加速度数据可用
if (self.motionManager.accelerometerAvailable)
{
// 主动请求获取加速度数据
CMAccelerometerData* accelerometerData = self.motionManager.accelerometerData;
self.accelerometerLabel.text = [NSString stringWithFormat:
@"加速度为\n-----------\nX轴: %+.2f\nY轴: %+.2f\nZ轴: %+.2f",
accelerometerData.acceleration.x,
accelerometerData.acceleration.y,
accelerometerData.acceleration.z];
}
// 如果CMMotionManager的陀螺仪数据可用
if (self.motionManager.gyroAvailable)
{
// 主动请求获取陀螺仪数据
CMGyroData* gyroData = self.motionManager.gyroData;
self.gyroLabel.text = [NSString stringWithFormat:
@"绕各轴的转速为\n--------\nX轴: %+.2f\nY轴: %+.2f\nZ轴: %+.2f",
gyroData.rotationRate.x,
gyroData.rotationRate.y,
gyroData.rotationRate.z];
}
// 如果CMMotionManager的磁场数据可用
if (self.motionManager.magnetometerAvailable)
{
// 主动请求获取磁场数据
CMMagnetometerData* magnetometerData = self.motionManager.magnetometerData;
self.magnetometerLabel.text = [NSString stringWithFormat:
@"磁场数据为\n--------\nX轴: %+.2f\nY轴: %+.2f\nZ轴: %+.2f",
magnetometerData.magneticField .x,
magnetometerData.magneticField .y,
magnetometerData.magneticField .z];
}
}
@end
=========================
===================================================
谢谢!!!