CMMotionManager noise reduction. iOS.

Rand Kruback Cartoons

CMMotionManager lets us access data from various motion sensors like accelerometer or gyroscope.

However, in many situations, the data we get is not smooth. Basically it contains noise. This article presents a way to smooth the accelerometer readings using a Low Pass Filter. Continue reading

Sending a JSON file to a HTTP server using POST. iOS.

This article shows how to use NSURLSession to perform a POST request that sends a JSON data to a HTTP server. It uses NSURLSession to create a NSURLSessionDataTask that POSTs the file. You can grab this code also from my gist repo.

// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/my.json"];

// Create a simple dictionary with numbers.
NSDictionary *dictionary = @{ @"numbers" : @[@1, @2, @3] };
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = JSONData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
                                                             completionHandler:^(NSData *data,
                                                                                 NSURLResponse *response,
                                                                                 NSError *error)
    if (!error)
        NSLog(@"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
        NSLog(@"Error: %@", error.localizedDescription);
// Start the task.
[task resume];

You might want to check out a simple HTTP server that I wrote in Python. It is described and available for download in this article. It basically saves the JSON you POST in a file so you can examine if the data was correctly sent.

I used it to test the code and JSON I sent was successfully saved.


What is the Advertising Identifier (IDFA) on iOS, how to use it, and why is it so important?

Apple has recently introduced a new question every developer is asked in iTunes Connect while creating app version. The new option is strictly connected with access to ASIdentifierManager to obtain a unique ID – Advertising Identifier (IDFA) – that is related to serving advertisements.

This article covers all the information you should know about the new policies, reasons behind introducing them, and DOs and DON’Ts to not get rejected while submitting the app.

What is IDFA?

Let’s decipher the acronym first. IDFA stands for Identifier for Advertising. Apple documentation says that IDFA is an identifier that can be used only for serving advertisements.

An alphanumeric string unique to each device, used only for serving advertisements.

It is similar to UIDevice’s property identifierForVendor but (and that’s a very big but) its value is the same for all vendors. In short words, it uniquely identifies the iDevice. However it is not the same as an old UDID which usage has been prohibited. IDFA can change in special cases. For example when user erases the device.

When to use IDFA?

You should only use IDFA for advertising related purposes. It should not be used solely for uniquely identifying the device. Not obeying this rule might result in rejection of your app from the App Store. Basically, if your app shows advertisements, uses iAd, or responds to advertisements in any way, for example by submitting an event to your server to indicate that it was launched because user tapped on an iAd, you are good to go.

You can use IDFA for:

  • frequency capping,
  • conversion events,
  • estimating the number of unique users,
  • security and fraud detection,
  • debugging

iTunes Connect

Recent change in iTunes Connect added a new question the developer has to answer before marking the version as ready for upload.

Does this app use the Advertising Identifier (IDFA)?


Answering YES results in showing three checkboxes where you can indicate why exactly your app needs to access the Advertising Identifier.

  • Serve advertisements within the app.
  • Attribute this app installation to a previously served advertisement.
  • Attribute an action taken within this app to a previously served advertisement.

First option is self explanatory. Check this if you are showing advertisements in your app. Next two options cover various cases when your app is opened because of user interaction with an ad. A good example is sending the identifier to your advertising system to know about conversion.

How to use IDFA?

Getting IDFA is simple. ASIdentifierManager class provides methods for getting it and checking whether user has decided to opt out from ad tracking. In this case, returned IDFA string is nil. The following code snippet shows how to obtain a string value of IDFA.

- (NSString *)identifierForAdvertising
   if([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled])
       NSUUID *IDFA = [[ASIdentifierManager sharedManager] advertisingIdentifier];
       return [IDFA UUIDString];
    return nil;

Don’t forget to link with AdSupport framework. If you only target iOS 7 and above, you can add it using modules.

@import AdSupport;


Apple takes security very seriously. New policies for collecting used specific information regarding advertising blend very well in it. User have now a choice to opt out from behavioral advertising. It is a move in the right direction.

If you have any questions or feel like some valuable information is missing here, please let me know about it in the comments.

SKScene and UIViewController. Delegation and notifications in Sprite Kit.

Planet_1A scene is the root node in a tree of Sprite Kit nodes. We implement our game logic there. However, there are many situations that SKScene needs to inform its view controller about some events or wants to force particular behavior only view controller can provide. This article shows how to make this communication work. And what is most important – how to do it in the cleanest possible way.
Continue reading

How to use UIGestureRecognizer to drag and drop views. iOS.

Drag and drop viewIn this tutorial I will explain how to use UIPanGestureRecognizer to drag and drop views. If you want to jump straight to the code you can download a fully working example project from here.

UIPanGestureRecognizer is a subclass of UIGestureRecognizer that specialises in detecting panning (dragging) gestures. A panning gesture can have 3 states.

It begins when user touched the screen and starts dragging. In this moment UIPanGestureRecognizer‘s state changes to UIGestureRecognizerStateBegan. Then, when user continues panning, state of gesture recognizer changes to UIGestureRecognizerStateChanged. Finally, when user released the finger, the gesture ends (UIGestureRecognizerStateEnded). We will use this in our handler method to move an instance of UIView along with the panning gesture.

Let’s start creating an empty project in Xcode. I chose Single View Application template and created a view in the center of the screen.
Continue reading

Detecting phone call status on iOS.

In this article I’m going to show how to use the CoreTelephony Framework to get notified when user started or finished a phone call while interacting with your app. Obviously, for security reasons we cannot know the number user calls but the information about call status might be useful. For example if you want to track if user really called a phone number you are showing in your app.

Core Telephony defines 4 states of a phone call:

extern NSString const *CTCallStateDialing;
extern NSString const *CTCallStateIncoming;
extern NSString const *CTCallStateConnected;
extern NSString const *CTCallStateDisconnected;

To get notified about these events we have to use CTCallCenter and implement a callEventHandler that will be fired when the call status changes. Here is how to do it.

First, we will need a CTCallCenter instance. A good place to declare it is application’s delegate:

@property(nonatomic, strong) CTCallCenter *callCenter;

Then, we have to set a callEventHandler when the app launches in application:didFinishLaunchingWithOptions:.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        _callCenter = [[CTCallCenter alloc] init];

        [_callCenter setCallEventHandler:^(CTCall *call)
             if ([call.callState isEqualToString: CTCallStateConnected])
             else if ([call.callState isEqualToString: CTCallStateDialing])
             else if ([call.callState isEqualToString: CTCallStateDisconnected])

             } else if ([call.callState isEqualToString: CTCallStateIncoming])

    return YES;

The callEventHandler block should support being invoked from any context since a phone call can happen at any time your application runs.

You can easily extend this code snippet to get duration of a phone call simply by saving NSDate with start and end event of a phone call and calculating the time interval between them.

Playing sounds in Sprite Kit using SKAction.

This article discusses adding sound effects to a Sprite Kit project using SKAction and provides you with a couple of tips and tricks and useful code snippets. It also explains performance issues that may appear when dealing with sounds not in the best, most efficient way and gives insights into how to avoid these problems.

Using SKAction

There are many ways you can play sounds in Sprite Kit game. The easiest way of playing a sound file is using a SKAction. It has a built-in method for handling audio playback.

+ (SKAction *)playSoundFileNamed:(NSString*)soundFile

The method simply creates an action that plays a sound. Sound file name must be the name or path of a file of a platform supported audio file format. Apple recommends using a LinearPCM format audio file with 8 or 16 bits per channel for best performance.
Continue reading

All you wanted to know about NSRunLoop. iOS.

This article explains in simple words, like to a rubber duck, what a run loop is in OS X and iOS.

What is a run loop?

A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.

That’s what docs say. Each thread, including the application’s main thread, has an associated run loop object. The app frameworks automatically set up and run the run loop on the main thread as part of the application startup process.
Continue reading

Why can’t crash reporting tools track Low Memory crashes on iOS.

There are hundreds of them. HockeyApp, QuincyKit, Crashlytics and many others. None are able to capture a low memory crashes. Why? This article will tell you this.

How crash reporting tools work.

Crash reporting tools look into one special folder in application’s directory. Continue reading

Sprite Kit’s coordinate system.

SpriteKit coordinatesThe coordinate system in Sprite Kit might give you a headache if you didn’t dig deep enough while reading the documentation.

In this post I will explain differences between SKScene and SKNode when it comes to coordinates.

Sprite Kit uses a coordinate orientation that starts from the bottom left corner of the screen (0, 0), and the x and y values increase as you move up and to the right.
Continue reading