iPhone

Redirecting NSLog to a log file

Using NSLog is all well and good for debugging iPhone OS applications when the device is connected to your Mac, but what about when it is not. Often you want to give builds of your application to people that don’t have Xcode installed (or can’t get the silly certificates to work !!!), or just as commonly, to test if the application works outside of your lovely office which has a perfect WiFi connection.

When I first thought about this problem, I was thinking along the lines of build a custom log function lets say MagicLog() and this calls a function that saves the string to a file. The problem with this is that I would have to go through all of my code and add MagicLog() to everywhere that I have NSLog(), that seemed a bit to verbose for my liking.

After searching on the internet I found out that (rather obvious) NSLog runs over standard error. This means that you are able to simply redirect standard error to a file using the ANSI function freopen().


FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict stream);

http://www.opengroup.org/onlinepubs/000095399/functions/freopen.html

Before we can save NSLog() to a file, we first have to find a place to save it. The best place to do this is the application’s documents folder. To get this you can use the following code snippet:


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Once we have the documents folder, we need to give a name to the file. To make it easy for me I just name it “the date”.log :


NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];

To make this into a valid path, use the NSString method stringByAppendingPathComponent


NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];

The last step is to redirect stderr to this file


freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);

To keep my code maintainable I keep all of this as a function, and I call it in my AppDelegate if I want to turn this functionality on.


- (void)redirectNSLogToDocumentFolder{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];

NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];

freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}


Getting the file.

Now that you have logged all the information you need, you will want to get this off of the device. Thankfully this is easy as well. Simply open the organiser in Xcode and select the device that is currently connected to your Mac.

A the bottom of the main pain there is an application section. Open the detail disclosure on the application you want to get the data from, and hit the little download button to the right of the Application Data package. You will be prompted to save this folder to your mac.

Warning:
Writing to the file system on the iPhone is slow, so this will effect the performance of your application. Therefore DO NOT ship an application with this in, or give it to people that can’t stand poor performance.

URL Encoding

If you have tried to send any information using a GET web request, you would have come across an annoying problem. That annoying problem is making sure that the URL is correctly encoded.

At first glance it would seem that the Cocoa Frameworks do this for you, and you would be right …. well kind of.

The issue is that by default most of these methods leave characters such as & = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request in valid.

Luckily there is a function in Core Foundation that helps:

CFStringRef CFURLCreateStringByAddingPercentEscapes (
CFAllocatorRef allocator,
CFStringRef originalString,
CFStringRef charactersToLeaveUnescaped,
CFStringRef legalURLCharactersToBeEscaped,
CFStringEncoding encoding
);

What makes this function useful, is the legalURLCharactersToBeEscaped parameter. This will escape legal characters such as & ? = if they are supplied. This allows you to escape parameters using the following code.

CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)parameter, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8)

An example of when to use this, is Twitters Update status API. You can find that here http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update

To update your status to the following:

This is my status

You would need to post up the following URL:

http://twitter.com/statuses/update.xml?status=This%20is%20my%20status

As this is such a common problem of mine, I have created a category on NSURL. This allows you to pass in a base URL and a parameters dictionary.

+ (NSURL *)URLWithBaseString:(NSString *)baseString parameters:(NSDictionary *)parameters{

NSMutableString *urlString =[NSMutableString string];

//The URL starts with the base string
[urlString appendString:baseString];

NSInteger keyIndex = 0;

for (id key in parameters) {

//First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an &
if(keyIndex ==0)
{
[urlString appendFormat:@"?%@=%@",key,CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8)];
}else{
[urlString appendFormat:@"&%@=%@",key,CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8)];
}

keyIndex++;
}

return [NSURL URLWithString:urlString];

}

Using a parameters dictionary keeps the code nice and clean, but beware, to use the category method above you still have to make sure that your keys, and the base URL are correctly encoded (no spaces or invalid characters !!!!!).

As we now have a category method to do all the hard work for us, to create the Twitter URL you just need to do the following:

NSString *baseString=@"http://twitter.com/statuses/update.xml";
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"This is my status",@"status",nil];
NSURL *url=[NSURL URLWithBaseString:baseString parameters:dictionary];

And thats it. Obviously this category can be used for things other than twitter ….. if you really want to.

Simple UIView based Animations on the iPhone

Although for complex animation sequences on the iPhone you need to use either the OpenGL or Apple’s very own Core Animation Framework, a lot of simple animations can be achieved with the methods found in the UIView class. All these animations are actually built upon Core Animation, but they have been wrapped up for you to use with very little code.

All animations triggered by the UIView class happen within a animation block.

To start an animation block you use the UIView Class method:

+ (void)beginAnimations:(NSString *)animationID context:(void *)context;

The animation ID is used in delegate call backs for such things as the beginning and end of animation blocks. The context is an additional piece of information that can be passed through.

As both of these parameters are optional, you comenly see:

[UIView beginAnimations:@"" context:NULL];

To commit these animations, and therefore end the animation block, you need to use the UIView class method:

+ (void)commitAnimations

So what types of animations can you do ? well quite a few.

You can animate views by:

  • Changing their alpha
  • Changing there size
  • Changing there location

In a single animation block you can animate multiple views, and you are also able to nest animation blocks.

So lets do a common example. When a UITableViewCell is being edited you often want to make a UILabel’s (label) alpha change to 0 so it is hidden:

[UIView beginAnimations:@"" context:NULL];
[label setAlpha:(editing ? 0.0 : 1.0)];
[UIView commitAnimations];

For those new to C programming:

(editing ? 0.0 : 1.0)

Is equivlant to:

if(editing)
{
0.0;
}else{
1.0;
}

So for the second example we also have a UILabel (label), that we want to grow when the animation code is run. We also want this animation to last 2 seconds, so the user can admire our work. In addition to this, we want the animation to “ease in”. This is known as the animation curve. The animation curves that are available are

  • ease in (slow then fast)
  • ease out (fast then slow)
  • ease in and out (slow, fast, slow)
  • linear (constant speed)

We would do this animation using the following animation block:

[UIView beginAnimations:@"" context:NULL];

//The new frame size
[label setFrame: CGRectMake(0,0,320,100)];

//The animation duration
[UIView setAnimationDuration:2.0];

[UIView setAnimationDelay: UIViewAnimationCurveEaseIn];

[UIView commitAnimations];

This is just a brief overview of the animations you can do using the UIView class, but it should be enough to get you started. The UIView methods also include delegate call backs for when an animation starts and end. For more information see Apple’s Documentation.

If the UIView class does not have what you need, you will probably need to use the Core Animation framework. While using this framework is not trivial, it is not as hard as using OpenGL (which is used commonly for 3D games), and you can build some fantastic animations using it.

Changing the name of an iPhone application

When you finally come to release your application after months of hard work, your might want to change the name of the application that appears on the iPhone springboard, and if you use it, the settings application.

To change the name of an iPhone application is very easy. Simply open the Xcode project, and then scroll down to the “Targets” section, which the the “Groups & Files” part of Xcode. Select the application’s target and “Get info” on it using cmd-i or ctrl clicking it, and select “Get Info” from the menu.

In the build section of the get info window, you need to change the “Product Name” value to whatever you want your application to be called. When you change this value make sure that the configuration pop up menu (at the top of the window) is set to “All Configurations”, so it takes effect in all of your builds.

For the change of name to take effect, simply clean your targets and rebuild your application.

Make your iPhone vibrate

One thing that took me a while to find out, was how to make an iPhone vibrate. In the end I found out that it is in the audio APIs, and it is just the one line of code.


AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);