继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

iOS/WatchOS 加速度数据获取

Realank刘
关注TA
已关注
手记 11
粉丝 11
获赞 446

最近在做一个有意思的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好像不能获取陀螺仪数据,具体原因暂时还没有研究

打开App,阅读手记
5人推荐
发表评论
随时随地看视频慕课网APP