Mac Developer Library

Developer

Foundation Framework Reference NSURLConnection Class Reference

Options
Deployment Target:

On This Page
Language:

NSURLConnection

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself.

The NSURLConnection class provides convenience class methods to load URL requests both asynchronously using a callback block and synchronously.

For greater control, you can create a URL connection object with a delegate object that conforms to the NSURLConnectionDelegate and NSURLConnectionDataDelegate protocols. The connection calls methods on that delegate to provide you with progress and status as the URL request is loaded asynchronously. The connection also calls delegate methods to let you override the connection’s default behavior (for example, specifying how a particular redirect should be handled). These delegate methods are called on the thread that initiated the asynchronous load operation.

For more information about errors, see the NSURLError.h header, Foundation Constants Reference, and URL Loading System Error Codes in Error Handling Programming Guide.

NSURLConnection Protocols

The NSURLConnection class works in tandem with three formal protocols: NSURLConnectionDelegate, NSURLConnectionDataDelegate, and NSURLConnectionDownloadDelegate. To use these protocols, you write a class that conforms to them and implement any methods that are appropriate, then provide an instance of that class as the delegate when you create a connection object.

The NSURLConnectionDelegate protocol is primarily used for credential handling, but also handles connection completion. Because it handles connection failure during data transfers, all connection delegates must typically implement this protocol.

In addition, unless you’re using Newsstand Kit, your delegate must also conform to the NSURLConnectionDataDelegate protocol, because this protocol provides methods that the NSURLConnection class calls with progress information during an upload, with fragments of the response data during a download, and to provide a new upload body stream if the server’s response necessitates a second connection attempt—for example, if NSURLConnection must retry the request with different credentials.

Finally, if you’re using Newsstand Kit, your delegate can conform to the NSURLConnectionDownloadDelegate protocol. This protocol provides support for continuing interrupted file downloads and receiving a notification whenever a download finishes. This protocol is solely for use with NSURLConnection objects created using Newsstand Kit’s downloadWithDelegate: method.

Inheritance


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in Mac OS X v10.2 with Safari 1.0 installed.
Available in Mac OS X v10.2.7 and later.
  • Returns whether a request can be handled based on a preflight evaluation.

    Declaration

    Swift

    class func canHandleRequest(_ request: NSURLRequest) -> Bool

    Objective-C

    + (BOOL)canHandleRequest:(NSURLRequest *)request

    Parameters

    request

    The request to evaluate. The connection deep-copies the request on creation.

    Return Value

    YEStrue if a preflight operation determines that a connection with request can be created and the associated I/O can be started, NOfalse otherwise.

    Discussion

    The result of this method is valid as long as no NSURLProtocol classes are registered or unregistered, and request remains unchanged. Applications should be prepared to handle failures even if they have performed request preflighting by calling this method.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.2 and later.

  • A deep copy of the original connection request. (read-only)

    Declaration

    Swift

    @NSCopying var originalRequest: NSURLRequest { get }

    Objective-C

    @property(readonly, copy) NSURLRequest *originalRequest

    Discussion

    As the connection performs the load, the request may change as a result of protocol canonicalization or due to following redirects. currentRequest can be used to retrieve this value.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.8 and later.

    See Also

    currentRequest

  • The current connection request. (read-only)

    Declaration

    Swift

    @NSCopying var currentRequest: NSURLRequest { get }

    Objective-C

    @property(readonly, copy) NSURLRequest *currentRequest

    Discussion

    As the connection performs the load, the request may change as a result of protocol canonicalization or due to following redirects. This property provides the current value of the request.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.8 and later.

    See Also

    originalRequest

  • Performs a synchronous load of the specified URL request.

    Declaration

    Swift

    class func sendSynchronousRequest(_ request: NSURLRequest, returningResponse response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>, error error: NSErrorPointer) -> NSData?

    Objective-C

    + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

    Parameters

    request

    The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.

    response

    Out parameter for the URL response returned by the server.

    error

    Out parameter used if an error occurs while processing the request. May be NULL.

    Return Value

    The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.

    Discussion

    A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

    If authentication is required in order to download the request, the required credentials must be specified as part of the URL. If authentication fails, or credentials are missing, the connection will attempt to continue without credentials.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.2 and later.

  • Creates and returns an initialized URL connection and begins to load the data for the URL request.

    Declaration

    Objective-C

    + (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate

    Parameters

    request

    The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.

    delegate

    The delegate object for the connection. The connection calls methods on this delegate as the load progresses. Delegate methods are called on the same thread that called this method. For the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode.

    Return Value

    The URL connection for the URL request. Returns nil if a connection can't be created.

    Special Considerations

    During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in OS X v10.2 and later.

  • Returns an initialized URL connection and begins to load the data for the URL request.

    Declaration

    Swift

    init?(request request: NSURLRequest, delegate delegate: AnyObject?)

    Objective-C

    - (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate

    Parameters

    request

    The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.

    delegate

    The delegate object for the connection. The connection calls methods on this delegate as the load progresses. Delegate methods are called on the same thread that called this method. By default, for the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode. See scheduleInRunLoop:forMode: to change the run loop and mode.

    Return Value

    The URL connection for the URL request. Returns nil if a connection can't be initialized.

    Discussion

    This is equivalent to calling initWithRequest:delegate:startImmediately: and passing YEStrue for startImmediately.

    Special Considerations

    During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.2 and later.

  • Returns an initialized URL connection and begins to load the data for the URL request, if specified.

    Declaration

    Swift

    init?(request request: NSURLRequest, delegate delegate: AnyObject?, startImmediately startImmediately: Bool)

    Objective-C

    - (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately

    Parameters

    request

    The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.

    delegate

    The delegate object for the connection. The connection calls methods on this delegate as the load progresses.

    startImmediately

    YEStrue if the connection should begin loading data immediately, otherwise NOfalse. If you pass NOfalse, the connection is not scheduled with a run loop. You can then schedule the connection in the run loop and mode of your choice by calling scheduleInRunLoop:forMode:.

    Return Value

    The URL connection for the URL request. Returns nil if a connection can't be initialized.

    Special Considerations

    During the download the connection maintains a strong reference to the delegate. It releases that strong reference when the connection finishes loading, fails, or is canceled.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.

  • Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.

    Declaration

    Swift

    class func sendAsynchronousRequest(_ request: NSURLRequest, queue queue: NSOperationQueue!, completionHandler handler: (NSURLResponse!, NSData!, NSError!) -> Void)

    Objective-C

    + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError))handler

    Parameters

    request

    The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.

    queue

    The operation queue to which the handler block is dispatched when the request completes or failed.

    handler

    The handler block to execute.

    Discussion

    If the request completes successfully, the data parameter of the handler block contains the resource data, and the error parameter is nil. If the request fails, the data parameter is nil and the error parameter contain information about the failure.

    If authentication is required in order to download the request, the required credentials must be specified as part of the URL. If authentication fails, or credentials are missing, the connection will attempt to continue without credentials.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.7 and later.

  • Causes the connection to begin loading data, if it has not already.

    Declaration

    Swift

    func start()

    Objective-C

    - (void)start

    Discussion

    Calling this method is necessary only if you create a connection with the initWithRequest:delegate:startImmediately: method and provide NOfalse for the startImmediately parameter. If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.

  • Cancels an asynchronous load of a request.

    Declaration

    Swift

    func cancel()

    Objective-C

    - (void)cancel

    Discussion

    After this method is called, the connection makes no further delegate method calls. If you want to reattempt the connection, you should create a new connection object.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.2 and later.

  • Determines the run loop and mode that the connection uses to call methods on its delegate.

    Declaration

    Swift

    func scheduleInRunLoop(_ aRunLoop: NSRunLoop, forMode mode: String)

    Objective-C

    - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

    Parameters

    aRunLoop

    The NSRunLoop instance to use when calling delegate methods.

    mode

    The mode in which to call delegate methods.

    Discussion

    By default, a connection is scheduled on the current thread in the default mode when it is created. If you create a connection with the initWithRequest:delegate:startImmediately: method and provide NOfalse for the startImmediately parameter, you can schedule the connection on a different run loop or mode before starting it with the start method. You can schedule a connection on multiple run loops and modes, or on the same run loop in multiple modes.

    You cannot reschedule a connection after it has started.

    It is an error to schedule delegate method calls with both this method and the setDelegateQueue: method.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.

  • Determines the operation queue that is used to call methods on the connection’s delegate.

    Declaration

    Swift

    func setDelegateQueue(_ queue: NSOperationQueue!)

    Objective-C

    - (void)setDelegateQueue:(NSOperationQueue *)queue

    Parameters

    queue

    The operation queue to use when calling delegate methods.

    Discussion

    By default, a connection is scheduled on the current thread in the default mode when it is created. If you create a connection with the initWithRequest:delegate:startImmediately: method and provide NOfalse for the startImmediately parameter, you can instead schedule the connection on an operation queue before starting it with the start method.

    You cannot reschedule a connection after it has started.

    It is an error to schedule delegate method calls with both this method and the scheduleInRunLoop:forMode: method.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.7 and later.

  • Causes the connection to stop calling delegate methods in the specified run loop and mode.

    Declaration

    Swift

    func unscheduleFromRunLoop(_ aRunLoop: NSRunLoop, forMode mode: String)

    Objective-C

    - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode

    Parameters

    aRunLoop

    The run loop instance to unschedule.

    mode

    The mode to unschedule.

    Discussion

    By default, a connection is scheduled on the current thread in the default mode when it is created. If you create a connection with the initWithRequest:delegate:startImmediately: method and provide NOfalse for the startImmediately parameter, you can instead schedule connection on a different run loop or mode before starting it with the start method. You can schedule a connection on multiple run loops and modes, or on the same run loop in multiple modes. Use this method to unschedule the connection from an undesired run loop and mode before starting the connection.

    You cannot reschedule a connection after it has started. It is not necessary to unschedule a connection after it has finished.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.