25.12.2013 Views

URL Loading System Programming Guide - Apple Developer

URL Loading System Programming Guide - Apple Developer

URL Loading System Programming Guide - Apple Developer

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using NS<strong>URL</strong>Connection<br />

Creating a Connection<br />

Listing 2-1<br />

Creating a connection using NS<strong>URL</strong>Connection<br />

// Create the request.<br />

NS<strong>URL</strong>Request *theRequest=[NS<strong>URL</strong>Request requestWith<strong>URL</strong>:[NS<strong>URL</strong><br />

<strong>URL</strong>WithString:@"http://www.apple.com/"]<br />

cachePolicy:NS<strong>URL</strong>RequestUseProtocolCachePolicy<br />

timeoutInterval:60.0];<br />

// Create the NSMutableData to hold the received data.<br />

// receivedData is an instance variable declared elsewhere.<br />

receivedData = [NSMutableData dataWithCapacity: 0];<br />

// create the connection with the request<br />

// and start loading the data<br />

NS<strong>URL</strong>Connection *theConnection=[[NS<strong>URL</strong>Connection alloc] initWithRequest:theRequest<br />

delegate:self];<br />

if (!theConnection) {<br />

// Release the receivedData object.<br />

receivedData = nil;<br />

}<br />

// Inform the user that the connection failed.<br />

The transfer starts immediately upon receiving the initWithRequest:delegate: message. It can be canceled<br />

any time before the delegate receives a connectionDidFinish<strong>Loading</strong>: or<br />

connection:didFailWithError: message by sending the connection a cancel message.<br />

When the server has provided sufficient data to create an NS<strong>URL</strong>Response object, the delegate receives a<br />

connection:didReceiveResponse: message. The delegate method can examine the provided<br />

NS<strong>URL</strong>Response object and determine the expected content length of the data, MIME type, suggested filename,<br />

and other metadata provided by the server.<br />

You should be prepared for your delegate to receive the connection:didReceiveResponse: message<br />

multiple times for a single connection; this can happen if the response is in multipart MIME encoding. Each<br />

time the delegate receives the connection:didReceiveResponse: message, it should reset any progress<br />

indication and discard all previously received data (except in the case of multipart responses). The example<br />

implementation in Listing 2-2 simply resets the length of the received data to 0 each time it is called.<br />

2013-10-22 | Copyright © 2003, 2013 <strong>Apple</strong> Inc. All Rights Reserved.<br />

33

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!