Contents

NSURLRequest

A URL load request that is independent of protocol or URL scheme.

Declaration

class NSURLRequest

Overview

Use this type in Swift when you need reference semantics or other Foundation-specific behavior.

NSURLRequest encapsulates two essential properties of a load request: the URL to load and the policies used to load it. In addition, for HTTP and HTTPS requests, URLRequest includes the HTTP method (GET, POST, and so on) and the HTTP headers. Finally, custom protocols can support custom properties as explained in Custom protocol properties.

NSURLRequest only represents information about the request. Use other classes, such as URLSession, to send the request to a server. See Fetching website data into memory and Uploading data to a website for an introduction to these techniques.

The mutable subclass of NSURLRequest is NSMutableURLRequest.

Reserved HTTP headers

The URL Loading System handles various aspects of the HTTP protocol for you (HTTP 1.1 persistent connections, proxies, authentication, and so on). As part of this support, the URL Loading System takes responsibility for certain HTTP headers:

  • Content-Length

  • Authorization

  • Connection

  • Host

  • Proxy-Authenticate

  • Proxy-Authorization

  • WWW-Authenticate

If you set a value for one of these reserved headers, the system may ignore the value you set, or overwrite it with its own value, or simply not send it. Moreover, the exact behavior may change over time. To avoid confusing problems like this, do not set these headers directly.

The URL Loading System sets the Content-Length header based on whether the request body has a known length:

  • If so, it uses the identity transfer encoding and sets the Content-Length header to that known length. You see this when you set the request body to a data object.

  • If not, it uses the chunked transfer encoding and omits the Content-Length header. You see this when you set the request body to a stream.

Custom protocol properties

If you implement a custom URL protocol by subclassing URLProtocol, and it needs protocol-specific properties, extend NSURLRequest with accessor methods for those custom properties. In your accessor methods, call property(forKey:in:) and setProperty(_:forKey:in:) to associate property values with the request.

Topics

Creating requests

Working with a cache policy

Accessing request components

Getting header fields

Controlling request behavior

Supporting limited modes

Accessing the service type

Supporting secure coding

Indicating the source of the request

Initializers

Instance Properties

See Also

Requests and responses