为了账号安全,请及时绑定邮箱和手机立即绑定

iOS/WatchOS 加速度数据获取

标签:
iOS

最近在做一个有意思的App,需要用到iPhone或者手表的加速度数据
所以总结一下分享给大家

使用加速度数据非常简单,首先引用头文件:

#import <CoreMotion/CoreMotion.h>

在当前的ViewController中添加一个strong属性的CMMotionManager实例

@property (nonatomic, strong) CMMotionManager *manager;

之所以强调使用强引用,是因为我一开始就入坑了,如果是局部变量,这个实例就会在数据反馈前被销毁,导致一直没有反馈数据。

然后初始化manager对象:

_manager = [[CMMotionManager alloc] init];

之后判断能不能用加速度传感器(陀螺仪传感器同理)

if (_manager.accelerometerAvailable) {
    //可以使用加速度传感器
}

然后,设置加速度数据获取的时间间隔:

_manager.accelerometerUpdateInterval = 0.1;

我们这里取100ms

最后,就是更新数据了:

[_manager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            CMAcceleration acc = accelerometerData.acceleration;
            //NSLog(@"%f,%f,%f",acc.x,acc.y,acc.x);
            NSString* x = [NSString stringWithFormat:@"x:%lf",acc.x];
            NSString* y = [NSString stringWithFormat:@"y:%lf",acc.y];
            NSString* z = [NSString stringWithFormat:@"z:%lf",acc.z];
 }];

这就是整个获取的过程,非常简单

附上全部代码:

//
//  InterfaceController.m
//  WatchMeature WatchKit Extension
//
//  Created by Realank on 16/1/25.
//  Copyright © 2016年 realank. All rights reserved.
//

#import "InterfaceController.h"
#import <CoreMotion/CoreMotion.h>
#import <WatchConnectivity/WatchConnectivity.h>
#import <HealthKit/HealthKit.h>

@interface InterfaceController()<WCSessionDelegate,HKWorkoutSessionDelegate>

@property (unsafe_unretained, nonatomic) IBOutlet WKInterfaceLabel *xLabel;
@property (unsafe_unretained, nonatomic) IBOutlet WKInterfaceLabel *yLabel;
@property (unsafe_unretained, nonatomic) IBOutlet WKInterfaceLabel *zLabel;

@property (nonatomic, strong) CMMotionManager *manager;
@property (nonatomic, strong) HKHealthStore *healthStore;
@end

@implementation InterfaceController

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    HKWorkoutSession *session = [[HKWorkoutSession alloc]initWithActivityType:HKWorkoutActivityTypeRunning  locationType:HKWorkoutSessionLocationTypeOutdoor];
    session.delegate = self;
    [self.healthStore startWorkoutSession:session];

}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];

    WCSession* session = [WCSession defaultSession];
    session.delegate = self;
    [session activateSession];

    _manager = [[CMMotionManager alloc] init];
    if (_manager.accelerometerAvailable) {
        NSLog(@"accelerometerAvailable");
        _manager.accelerometerUpdateInterval = 0.1;
        __block BOOL sendSuccess = YES;
        [_manager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            CMAcceleration acc = accelerometerData.acceleration;
            //NSLog(@"%f,%f,%f",acc.x,acc.y,acc.x);
            NSString* x = [NSString stringWithFormat:@"x:%lf",acc.x];
            NSString* y = [NSString stringWithFormat:@"y:%lf",acc.y];
            NSString* z = [NSString stringWithFormat:@"z:%lf",acc.z];

            dispatch_async(dispatch_get_main_queue(), ^{

                [self.xLabel setText:x];
                [self.yLabel setText:y];
                [self.zLabel setText:z];
                if (sendSuccess) {
                    sendSuccess = NO;
                    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[x,y,z] forKeys:@[@"x",@"y",@"z"]];
                    [session sendMessage:dict replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
                        sendSuccess = YES;
                    } errorHandler:^(NSError * _Nonnull error) {

                    }];
                }

            });

        }];
    }

}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message {

}

- (void)workoutSession:(HKWorkoutSession *)workoutSession didFailWithError:(NSError *)error {

}

@end

iOS和WatchOS关于加速度传感器的数据获取,代码是一样的,
但是WatchOS好像不能获取陀螺仪数据,具体原因暂时还没有研究

点击查看更多内容
5人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
11
获赞与收藏
446

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消