O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required