9.4. Modifying a URL Request with NSMutableURLRequest

Problem

You want to adjust various HTTP headers and settings of a URL request before passing it to a URL connection.

Solution

This technique is the basis of many useful recipes shown later in this chapter. Use NSMutableURLRequest instead of NSURLRequest.

Discussion

A URL request can be either mutable or immutable. A mutable URL request can be changed after it has been allocated and initialized, whereas an immutable URL request cannot. Mutable URL requests are the target of this recipe. You can create them using the NSMutableURLRequest class.

Let’s have a look at an example where we will change the timeout interval of a URL request after we have allocated and initialized it:

NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];

Now let’s have a look at another example where we set the URL and the timeout of a URL request after it has been allocated and initialized:

NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setURL:url];

In other recipes in this chapter, we will have a look at some of the really neat tricks that we can perform using mutable URL requests.

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.