Category Archives: iOS



How to detect if the device is an iPhone 5

The iPhone5 introduced a new resolution to support in our iOS applications. The IPhone 5 resolution is 640x1136px at 4 inch screen, which makes it more elongated than in previous devices.

You may want to detect if the application is being used from an iPhone 5 and change the behavior of an element.

There are some ways to do, this is one of them:

1
#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height-568) ? NO : YES)

We have defined a constant that will help us to detect the resolution of the iPhone 5. In our code we’ll just use an if block to act accordingly.

1
2
3
4
5
6
7
8
if (IS_IPHONE5)
{
    // The app is running on iPhone 5
}
else
{
    // Not an iPhone 5
}

Playing a system sound in iOS app

We are going to play a system sound from our iOS app. You don’t always need to add to your iPhone or iPad application a audio track to play a sound, because the system has sounds that we can use in our application.

In this case, we are going to play the typical sound “beep“. To do this we will use the AudioToolbox framework.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import <AudioToolbox/AudioToolbox.h>
 
SystemSoundID mBeep;
 
// Create the sound
NSString* path = [[NSBundle mainBundle] 
                     pathForResource:@"Beep" ofType:@"aiff"];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mBeep);
 
// Play the sound
AudioServicesPlaySystemSound(mBeep);
 
// Dispose of the sound
AudioServicesDisposeSystemSoundID(mBeep);

In the official documentation you can read more about this topic, and you can also add vibration to these alerts.

How to shuffle a NSMutableArray [Objective-C]

The Objective-C NSArray object doesn’t have a specific function to shuffle the elements of the array.

With this simple code we can shuffle one NSMutableArray randomly. We will use the exchangeObjectAtIndex method for exchange items within the array and arc4random to get a random number we use to exchange items.

1
2
3
4
5
6
7
/* myArray is a NSMutableArray with some objects */
NSUInteger count = [myArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (arc4random() % nElements) + i;
	[myArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

Very useful, right? 🙂