Tôi đang sử dụng phương thức UIAccelerotmeterDelegate
accelerometer:didAccelerate:
nhưng gần đây phương pháp đó đã không được chấp nhận trong iOS 5.0. Vậy cách khác để lấy dữ liệu gia tốc là gì? Các tài liệu không đề cập đến thay thế chúng tôi có nghĩa vụ phải sử dụng.Làm cách nào để lấy dữ liệu gia tốc trong IOS?
11
A
Trả lời
13
Bạn nên sử dụng Core Motion framework (được giới thiệu trong iOS 4.0) làm sản phẩm thay thế. Tạo một thể hiện của CMMotionManager
và báo cho số điện thoại startAccelerometerUpdatesToQueue:withHandler:
, chuyển số NSOperationQueue
và một khối sẽ được thực hiện trên hàng đợi được chỉ định bất cứ khi nào có sẵn dữ liệu gia tốc kế mới.
5
Dường như UIAccelerometer và UIAccelerometerDelegate được thay thế bằng khuôn khổ CoreMotion.
Bạn có thể tìm thấy câu trả lời ở đây:
Why is accelerometer:didAccelerate: deprecated in IOS5?
Tôi Hy vọng nó giúp.
3
Được thay thế bằng CoreMotion
. Xem Motion Events.
4
Đây là mã mẫu hữu ích mà tôi tìm thấy cho CoreMotion từ liên kết this.
@interface ViewController()
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) IBOutlet UILabel *xAxis;
@property (nonatomic, strong) IBOutlet UILabel *yAxis;
@property (nonatomic, strong) IBOutlet UILabel *zAxis;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.accelerometerUpdateInterval = 1;
if ([self.motionManager isAccelerometerAvailable])
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
self.xAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.x];
self.yAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.y];
self.zAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.z];
});
}];
} else
NSLog(@"not active");
}
@end
1
Thêm khung CoreMotion vào dự án trước. Sau đó:
#import <CoreMotion/CoreMotion.h>
@property (strong, nonatomic) CMMotionManager *motionManager;
- (void)viewDidLoad {
_motionManager = [CMMotionManager new];
_motionManager.accelerometerUpdateInterval = 0.01; // 0.01 = 1s/100 = 100Hz
if ([_motionManager isAccelerometerAvailable])
{
NSOperationQueue *queue = [NSOperationQueue new];
[_motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error){
NSLog(@"X = %0.4f, Y = %.04f, Z = %.04f",
accelerometerData.acceleration.x,
accelerometerData.acceleration.y,
accelerometerData.acceleration.z);
}];
}
}