I am using the UIAccelerotmeterDelegate method accelerometer:didAccelerate: but recently that method has been deprecated in iOS 5.0. So what is the alternative way to get the accelerometer data? The documentation does not mention the alternative we are supposed to use.
You should use the Core Motion framework (introduced in iOS 4.0) as a substitue. Create an instance of CMMotionManager and tell it to startAccelerometerUpdatesToQueue:withHandler:, passing it an NSOperationQueue and a block that will be executed on the specified queue whenever new accelerometer data is available.
It seems that UIAccelerometer and UIAccelerometerDelegate were replaced by the CoreMotion framework.
You can find the answer here:
Why is accelerometer:didAccelerate: deprecated in IOS5?
I Hope it helps.
Here is a useful sample code I found for CoreMotion from this link.
#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
Its replaced by CoreMotion. See Motion Events.
Add CoreMotion framework to the project first. Then:
#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);
}];
}
}
I am answering this for Swift 5.x.
#available(iOS, introduced: 2.0, deprecated: 13.0, message: "UIAcceleration has been replaced by the CoreMotion framework") public protocol UIAccelerometerDelegate : NSObjectProtocol { }
Add CoreMotion framework only. Don't conform to UIAccelerometerDelegate.
import CoreMotion
If you want to show animation or create a game, you can start with the following code.
self.motionManager = CMMotionManager()
self.motionManager?.startAccelerometerUpdates()
if motionManager.isAccelerometerAvailable {
motionManager.startAccelerometerUpdates(to: .main) { (data, error) in
if let myData = data {
let x = String(format: "%.3f",myData.acceleration.x)
let y = String(format: "%.3f",myData.acceleration.y)
let z = String(format: "%.3f",myData.acceleration.z)
DispatchQueue.main.async {
var rect = self.anyObject.frame
let movetoX = rect.origin.x + CGFloat(myData.acceleration.x * stepMoveFactor)
let movetoY = rect.origin.y - CGFloat(myData.acceleration.y * stepMoveFactor)
if ( movetoX > 0 && movetoX < SCREEN_WIDTH ) {
rect.origin.x += CGFloat(myData.acceleration.x * stepMoveFactor)
}
if ( movetoY > 1 && movetoY < maxY ) {
rect.origin.y -= CGFloat(myData.acceleration.y * stepMoveFactor) }
}
}
}
}
use UIView.animate if you want. This method initiates a set of animations to perform on the view. The block object in the animations parameter contains the code for animating the properties of one or more views.
swift ios
Related
I've found very limited resources on this topic (CMPedometer). I was wondering if anyone here has managed to get this to work properly. My code is fairly simple, and has more than what I'm trying to do. Basically, the step counter does not increment EVERY step a user takes.
It actually is tracking every step the user takes but it updates so slowly and I can't figure out why. I even tried using NSTimer to make a request to update the labels every half a second. I want to try to get the step counter to update as a user takes a step. Here is my code...
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
#interface ViewController ()
#property (nonatomic, strong) CMPedometer *pedometer;
#property (nonatomic, weak) IBOutlet UILabel *startDateLabel;
#property (nonatomic, weak) IBOutlet UILabel *endDateLabel;
#property (nonatomic, weak) IBOutlet UILabel *stepsLabel;
#property (nonatomic, weak) IBOutlet UILabel *distanceLabel;
#property (nonatomic, weak) IBOutlet UILabel *ascendedLabel;
#property (nonatomic, weak) IBOutlet UILabel *descendedLabel;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if ([CMPedometer isStepCountingAvailable]) {
self.pedometer = [[CMPedometer alloc] init];
[NSTimer scheduledTimerWithTimeInterval:0.5f
target:self
selector:#selector(recursiveQuery)
userInfo:nil
repeats:YES];
} else {
NSLog(#"Nothing available");
self.startDateLabel.text = #"";
self.endDateLabel.text = #"";
self.stepsLabel.text = #"";
self.distanceLabel.text = #"";
self.ascendedLabel.text = #"";
self.descendedLabel.text = #"";
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.pedometer startPedometerUpdatesFromDate:[NSDate date]
withHandler:^(CMPedometerData *pedometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"data:%#, error:%#", pedometerData, error);
});
}];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.pedometer stopPedometerUpdates];
}
- (NSString *)stringWithObject:(id)obj {
return [NSString stringWithFormat:#"%#", obj];
}
- (NSString *)stringForDate:(NSDate *)date {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
return [formatter stringFromDate:date];
}
- (void)queryDataFrom:(NSDate *)startDate toDate:(NSDate *)endDate {
[self.pedometer queryPedometerDataFromDate:startDate
toDate:endDate
withHandler:
^(CMPedometerData *pedometerData, NSError *error) {
NSLog(#"data:%#, error:%#", pedometerData, error);
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"Error = %#",error.userInfo);
self.startDateLabel.text = #"";
self.endDateLabel.text = #"";
self.stepsLabel.text = #"";
self.distanceLabel.text = #"";
self.ascendedLabel.text = #"";
self.descendedLabel.text = #"";
} else {
self.startDateLabel.text = [self stringForDate:pedometerData.startDate];
self.endDateLabel.text = [self stringForDate:pedometerData.endDate];
self.stepsLabel.text = [self stringWithObject:pedometerData.numberOfSteps];
self.distanceLabel.text = [NSString stringWithFormat:#"%.1f[m]", [pedometerData.distance floatValue]];
self.ascendedLabel.text = [self stringWithObject:pedometerData.floorsAscended];
self.descendedLabel.text = [self stringWithObject:pedometerData.floorsDescended];
}
});
}];
}
- (void)recursiveQuery {
NSDate *to = [NSDate date];
NSDate *from = [to dateByAddingTimeInterval:-(24. * 3600.)];
[self queryDataFrom:from toDate:to];
}
Thanks in advance for any feedback!
EDIT
It seems the appropriate method to use for live updates is the following..
- (void)liveSteps {
[self.pedometer startPedometerUpdatesFromDate:[NSDate date]
withHandler:^(CMPedometerData *pedometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Steps %#",pedometerData.numberOfSteps);
});
}];
}
However, even this is severely delayed. Does anyone have any idea how to use this properly to essentially update as the user takes a step?
I can only confirm your findings. I also wanted to get "true" realtime information. As it seems at this point, the API is not capable of this; even by forcing the updates into a queue, sync, async, etc.
For references and others with this question, here is the code I use based on Swift 3 and Xcode 8.2. I simply apply this portion of code in the concerned viewcontroller, after checking the CMPedometer.isStepCountingAvailable().
As you can see, I've included a small animation to update the UILabel in a more fluid manner.
// Steps update in near realtime - UILabel
self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if(error == nil){
self.todaySteps.text = "\(data!.numberOfSteps)"
// Animate the changes of numbers in the UILabel
UILabel.transition(with: self.todaySteps,
duration: 0.50,
options: .transitionCrossDissolve,
animations: nil,
completion: nil)
}
})
}
I have a ContentPageViewController class, it has the IBOutlet stuff. I write my getter of ContentPageViewController in the ViewController like the following code.
ContentPageViewController.h
#interface ContentPageViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *busName;
#property (weak, nonatomic) IBOutlet UILabel *busTime;
#property (weak, nonatomic) IBOutlet UILabel *busType;
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// instantiation from a storyboard
ContentPageViewController *page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
self.page = page;
// send url request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://api.apb-shuttle.info/now" ]];
[self sendURLRequest:request];
// add the view of ContendPageViewController into ViewController
[self.view addSubview:self.page.view];
}
// It works if i remove the following code
- (ContentPageVC *)page
{
if (_page) _page = [[ContentPageViewController alloc] init];
return _page;
}
Nothing happened when I updated it. And it gave me a nil.
- (void)updateUI
{
// I got null here
NSLog("%#", self.page.busName)
// The spacing style font
NSDictionary *titleAttributes = #{
NSKernAttributeName: #10.0f
};
NSDictionary *attributes = #{
NSKernAttributeName: #5.0f
};
self.page.busName.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.name
attributes:titleAttributes];
self.page.busTime.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.depart
attributes:titleAttributes];
self.page.busType.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.note
attributes:attributes];
}
The following code is when I called the updateUI:
- (void)sendURLRequest:(NSURLRequest *)requestObj
{
isLoading = YES;
[RequestHandler PerformRequestHandler:requestObj withCompletionHandler:^(NSDictionary *data, NSError *error) {
if (!error) {
bus = [JSONParser JSON2Bus:data];
// Add the bus object into the array.
[self.busArray addObject: bus];
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
[self updateUI];
isLoading = NO;
}];
} else {
NSLog(#"%#", [error localizedDescription]);
}
}];
}
But it worked if I removed the getter above.
I have no idea how it works, please give me some hint. Thanks.
Check your IBOutlet is connected.
Check the method you are calling isn't called before the view is created from the storyboard/nib
EDIT
The lines of code that you added, are overriding your getter. And every time you call self.page, your creating a new instance!
// It works if i remove the following code
- (ContentPageVC *)page
{
if (_page) _page = [[ContentPageViewController alloc] init];
return _page;
}
It should be like so:
// It works if i remove the following code
- (ContentPageVC *)page
{
if (!_page) _page = [[ContentPageViewController alloc] init]; // Added the ! mark, only if nil you would create a new instance.
return _page;
}
Plus you are calling alloc init on it, so Its not the same instance from storyboard!
So you should do this:
- (ContentPageVC *)page
{
if (!_page) _page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
return _page;
}
And remove this lines of code:
// instantiation from a storyboard
ContentPageViewController *page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
self.page = page;
Every time you call "self.page" the override getter function will call. and return the same instance.
Is there anyway to check the value of 'type' variable with completionHandler.
-(void)sendApiMethod:(NSString*)apiName ApiType:(NSString*)type
{
[SendAPI setAPIWithName:#"APIName" completionHandler:^(NSArray *errors) {
if([type isEqualToString:#"Login"])
{
/// Call Some Other function
}
}];
}
I wrote a small piece of code to verify if works (only reading your question I would say yes as Droppy)
I added all there code in a ViewController in a Simple View App.
some assumption:
- all code there for sake of semplicity ....
- I have added a singleton as it seems You are calling a class method.
- instance method is a bit rough, it simply saves name and block
- I added a typedef for blocks to better reading it.
#import "ViewController.h"
typedef void (^CompletionBlock)(NSArray *errors);
#interface SendAPI : NSObject
-(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
+(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
+(SendAPI*)sharedInstance;
#property (strong) CompletionBlock completionBlock;
#property (strong) NSString * name;
#end
#implementation SendAPI : NSObject
static SendAPI * _singleton = nil;
+(SendAPI*)sharedInstance
{
if (_singleton == nil)
{
_singleton = [[SendAPI alloc] init];
}
return _singleton;
}
-(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
{
self.completionBlock = completionHandler;
self.name = [name copy];
__weak SendAPI * weakRef = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSError* err = [NSError errorWithDomain: #"delayed"
code:1111
userInfo: #{#"info": self.name}
];
weakRef.completionBlock(#[err]);
});
}
+(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
{
[[SendAPI sharedInstance]setAPIWithName:name completionHandler:completionHandler];
}
#end
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self sendApiMethod:#"HELLO" ApiType: #"Login"];
}
-(void)sendApiMethod:(NSString*)apiName ApiType:(NSString*)type{
[SendAPI setAPIWithName:#"APIName" completionHandler:^(NSArray *errors) {
if([type isEqualToString:#"Login"])
{
/// Call Some Other function
NSLog(#"%#", errors);
}
}];
}
it does LOG correctly
I've found very limited resources on this topic (CMPedometer). I was wondering if anyone here has managed to get this to work properly. My code is fairly simple, and has more than what I'm trying to do. Basically, the step counter does not increment EVERY step a user takes.
It actually is tracking every step the user takes but it updates so slowly and I can't figure out why. I even tried using NSTimer to make a request to update the labels every half a second. I want to try to get the step counter to update as a user takes a step. Here is my code...
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
#interface ViewController ()
#property (nonatomic, strong) CMPedometer *pedometer;
#property (nonatomic, weak) IBOutlet UILabel *startDateLabel;
#property (nonatomic, weak) IBOutlet UILabel *endDateLabel;
#property (nonatomic, weak) IBOutlet UILabel *stepsLabel;
#property (nonatomic, weak) IBOutlet UILabel *distanceLabel;
#property (nonatomic, weak) IBOutlet UILabel *ascendedLabel;
#property (nonatomic, weak) IBOutlet UILabel *descendedLabel;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if ([CMPedometer isStepCountingAvailable]) {
self.pedometer = [[CMPedometer alloc] init];
[NSTimer scheduledTimerWithTimeInterval:0.5f
target:self
selector:#selector(recursiveQuery)
userInfo:nil
repeats:YES];
} else {
NSLog(#"Nothing available");
self.startDateLabel.text = #"";
self.endDateLabel.text = #"";
self.stepsLabel.text = #"";
self.distanceLabel.text = #"";
self.ascendedLabel.text = #"";
self.descendedLabel.text = #"";
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.pedometer startPedometerUpdatesFromDate:[NSDate date]
withHandler:^(CMPedometerData *pedometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"data:%#, error:%#", pedometerData, error);
});
}];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.pedometer stopPedometerUpdates];
}
- (NSString *)stringWithObject:(id)obj {
return [NSString stringWithFormat:#"%#", obj];
}
- (NSString *)stringForDate:(NSDate *)date {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
return [formatter stringFromDate:date];
}
- (void)queryDataFrom:(NSDate *)startDate toDate:(NSDate *)endDate {
[self.pedometer queryPedometerDataFromDate:startDate
toDate:endDate
withHandler:
^(CMPedometerData *pedometerData, NSError *error) {
NSLog(#"data:%#, error:%#", pedometerData, error);
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"Error = %#",error.userInfo);
self.startDateLabel.text = #"";
self.endDateLabel.text = #"";
self.stepsLabel.text = #"";
self.distanceLabel.text = #"";
self.ascendedLabel.text = #"";
self.descendedLabel.text = #"";
} else {
self.startDateLabel.text = [self stringForDate:pedometerData.startDate];
self.endDateLabel.text = [self stringForDate:pedometerData.endDate];
self.stepsLabel.text = [self stringWithObject:pedometerData.numberOfSteps];
self.distanceLabel.text = [NSString stringWithFormat:#"%.1f[m]", [pedometerData.distance floatValue]];
self.ascendedLabel.text = [self stringWithObject:pedometerData.floorsAscended];
self.descendedLabel.text = [self stringWithObject:pedometerData.floorsDescended];
}
});
}];
}
- (void)recursiveQuery {
NSDate *to = [NSDate date];
NSDate *from = [to dateByAddingTimeInterval:-(24. * 3600.)];
[self queryDataFrom:from toDate:to];
}
Thanks in advance for any feedback!
EDIT
It seems the appropriate method to use for live updates is the following..
- (void)liveSteps {
[self.pedometer startPedometerUpdatesFromDate:[NSDate date]
withHandler:^(CMPedometerData *pedometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Steps %#",pedometerData.numberOfSteps);
});
}];
}
However, even this is severely delayed. Does anyone have any idea how to use this properly to essentially update as the user takes a step?
I can only confirm your findings. I also wanted to get "true" realtime information. As it seems at this point, the API is not capable of this; even by forcing the updates into a queue, sync, async, etc.
For references and others with this question, here is the code I use based on Swift 3 and Xcode 8.2. I simply apply this portion of code in the concerned viewcontroller, after checking the CMPedometer.isStepCountingAvailable().
As you can see, I've included a small animation to update the UILabel in a more fluid manner.
// Steps update in near realtime - UILabel
self.pedoMeter.startUpdates(from: midnightOfToday) { (data: CMPedometerData?, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if(error == nil){
self.todaySteps.text = "\(data!.numberOfSteps)"
// Animate the changes of numbers in the UILabel
UILabel.transition(with: self.todaySteps,
duration: 0.50,
options: .transitionCrossDissolve,
animations: nil,
completion: nil)
}
})
}
New to the site and Obj C. Attempting to get a pitch value from Device Motion (working), put into an array with the most recent 60 values (not working) and select the maximum value within the array. With each new pitch value from the device, new pitch value is added to the array and the 61st value is dropped. When I hook up my phone and run, I get the log values for the pitch and maxPitch; however, I am not getting the array of 60 values so I don't believe it is working properly. Any help is greatly appreciated.
I believe the problem may be in the line : if (pitchArray.count <= 60) {
[pitchArray addObject:[NSString stringWithFormat:#"%.2gº", motion.attitude.pitch * kRadToDeg]];
Here is the full code:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
#define kRadToDeg 57.2957795
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *pitchLabel;
#property (nonatomic, strong) CMMotionManager *motionManager;
#end
#implementation ViewController
- (CMMotionManager *)motionManager
{
if (!_motionManager) {
_motionManager = [CMMotionManager new];
[_motionManager setDeviceMotionUpdateInterval:1/60];
}
return _motionManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
self.pitchLabel.text = [NSString stringWithFormat:#"%.2gº", motion.attitude.pitch * kRadToDeg];
NSMutableArray *pitchArray = [NSMutableArray array];
pitchArray = [[NSMutableArray alloc] initWithCapacity:60];
if (pitchArray.count <= 60) {
[pitchArray addObject:[NSString stringWithFormat:#"%.2gº", motion.attitude.pitch * kRadToDeg]];
}
else {
[pitchArray removeObjectAtIndex:0];
}
NSNumber *maxPitch = [pitchArray valueForKeyPath:#"#max.intValue"];
NSLog(#"%#",pitchArray);
NSLog(#"Max Pitch Value = %d",[maxPitch intValue]);
}];
}
#end
You keep allocating a new array every time you get a new pitch value. So you shall define the pitch array as a property and allocate it before your motion update handler. Your code would be:
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *pitchLabel;
#property (nonatomic, strong) CMMotionManager *motionManager;
#property (nonatomic, strong) NSMutableArray *pitchArray;
#end
#implementation ViewController
- (CMMotionManager *)motionManager
{
if (!_motionManager) {
_motionManager = [CMMotionManager new];
[_motionManager setDeviceMotionUpdateInterval:1/60];
}
return _motionManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.pitchArray = [[NSMutableArray alloc] initWithCapacity:60];
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
self.pitchLabel.text = [NSString stringWithFormat:#"%.2gº", motion.attitude.pitch * kRadToDeg];
if (self.pitchArray.count <= 60) {
[self.pitchArray addObject:[NSString stringWithFormat:#"%.2gº", motion.attitude.pitch * kRadToDeg]];
}
else {
[self.pitchArray removeObjectAtIndex:0];
}
NSNumber *maxPitch = [self.pitchArray valueForKeyPath:#"#max.intValue"];
NSLog(#"%#",self.pitchArray);
NSLog(#"Max Pitch Value = %d",[maxPitch intValue]);
}];
}
Ah, simple error. It wasn't looping so I changed the if/else statement to while. The code works now and outputs the 60 item array and max value.