Inherits from NSObject
Conforms to RKConfigurationDelegate
Declared in RKClient.h
RKClient.m

Overview

RKClient exposes the low level client interface for working with HTTP servers and RESTful services. It wraps the request/response cycle with a clean, simple interface.

RKClient can be thought of as analogous to a web browser or other HTTP user agent. The client’s primary purpose is to configure and dispatch requests to a remote service for processing in a global way. When working with the Network layer, a user will generally construct and dispatch all RKRequest objects via the interfaces exposed by RKClient.

Base URL and Resource Paths

Core to an effective utilization of RKClient is an understanding of the Base URL and Resource Path concepts. The Base URL forms the common beginning part of a complete URL string that is used to access a remote web service. RKClient instances are configured with a Base URL and all requests dispatched through the client will be sent to a URL consisting of the base URL plus the resource path specified. The resource path is simply the remaining part of the URL once all common text is removed.

For example, given a remote web service at http://restkit.org and RESTful services at http://restkit.org/services and http://restkit.org/objects, our base URL would be http://restkit.org and we would have resource paths of /services and /objects.

Base URLs simplify interaction with remote services by freeing us from having to interpolate strings and construct NSURL objects to get work done. We are also able to quickly retarget an entire application to a different server or API version by changing the base URL. This is commonly done via conditional compilation to create builds against a staging and production server, for example.

Memory Management

Note that memory management of requests sent via RKClient instances are automatically managed for you. When sent, the request is retained by the requestQueue and is released when all request processing has completed. Generally speaking this means that you can dispatch requests and work with the response in the delegate methods without regard for memory management.

Request Serialization

RKClient and RKRequest support the serialization of objects into payloads to be sent as the body of a request. This functionality is commonly used to provide a dictionary of simple values to be encoded and sent as a form encoding with POST and PUT operations. It is worth noting however that this functionality is provided via the RKRequestSerializable protocol and is not specific to NSDictionary objects.

Sending Asynchronous Requests

A handful of methods are provided as a convenience to cover the common asynchronous request tasks. All other request needs should instantiate a request via [RKClient requestWithResourcePath:] and work with the RKRequest object directly.

Tasks

Initializing a Client

Configuring the Client

  •   baseURL

    The base URL all resources are nested underneath. All requests created through the client will their URL built by appending a resourcePath to the baseURL to form a complete URL.

    property
  •   HTTPHeaders

    A dictionary of headers to be sent with each request

    property
  •   timeoutInterval

    An optional timeout interval within which the request should be cancelled.

    property
  •   requestQueue

    The request queue to push asynchronous requests onto.

    property
  •   runLoopMode

    The run loop mode under which the underlying NSURLConnection is performed

    property
  •   defaultHTTPEncoding

    The default value used to decode HTTP body content when HTTP headers received do not provide information on the content. This encoding will be used by the RKResponse when creating the body content

    property
  • – setValue:forHTTPHeaderField:

    Adds an HTTP header to each request dispatched through the client

Handling SSL Validation

Authentication

  •   authenticationType

    The type of authentication to use for this request.

    property
  •   username

    The username to use for authentication via HTTP AUTH.

    property
  •   password

    The password to use for authentication via HTTP AUTH.

    property

OAuth1 Secrets

OAuth2 Secrets

Reachability & Service Availability Alerting

Reachability helpers

Caching

  •   cache

    An instance of the request cache used to store/load cacheable responses for requests sent through this client

    property
  •   requestCache

    An instance of the request cache used to store/load cacheable responses for requests sent through this client

    property
  •   cacheTimeoutInterval

    The timeout interval within which the requests should not be sent and the cached response should be used.

    property
  •   cachePolicy

    The default cache policy to apply for all requests sent through this client

    property
  •   cachePath

    The path used to store response data for this client’s request cache.

    property

Shared Client Instance

Building Requests

Sending Asynchronous Requests

Constructing Resource Paths and URLs

Other Methods

Properties

HTTPHeaders

A dictionary of headers to be sent with each request

@property (nonatomic, retain, readonly) NSMutableDictionary *HTTPHeaders

Declared In

RKClient.h

OAuth1AccessToken

The OAuth 1.0 access token

@property (nonatomic, retain) NSString *OAuth1AccessToken

Discussion

Used to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth1

Declared In

RKClient.h

OAuth1AccessTokenSecret

The OAuth 1.0 access token secret

@property (nonatomic, retain) NSString *OAuth1AccessTokenSecret

Discussion

Used to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth1

Declared In

RKClient.h

OAuth1ConsumerKey

The OAuth 1.0 consumer key

@property (nonatomic, retain) NSString *OAuth1ConsumerKey

Discussion

Used to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth1

Declared In

RKClient.h

OAuth1ConsumerSecret

The OAuth 1.0 consumer secret

@property (nonatomic, retain) NSString *OAuth1ConsumerSecret

Discussion

Used to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth1

Declared In

RKClient.h

OAuth2AccessToken

The OAuth 2.0 access token

@property (nonatomic, retain) NSString *OAuth2AccessToken

Discussion

Used to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth2

Declared In

RKClient.h

OAuth2RefreshToken

The OAuth 2.0 refresh token

@property (nonatomic, retain) NSString *OAuth2RefreshToken

Discussion

Used to retrieve a new access token before expiration and to build an Authorization header when authenticationType is RKRequestAuthenticationTypeOAuth2

Bug: NOT IMPLEMENTED: This functionality is not yet implemented.

Declared In

RKClient.h

additionalRootCertificates

A set of additional certificates to be used in evaluating server SSL certificates.

@property (nonatomic, retain, readonly) NSSet *additionalRootCertificates

Declared In

RKClient.h

authenticationType

The type of authentication to use for this request.

@property (nonatomic, assign) RKRequestAuthenticationType authenticationType

Discussion

This must be assigned one of the following:

  • RKRequestAuthenticationTypeNone: Disable the use of authentication
  • RKRequestAuthenticationTypeHTTP: Use NSURLConnection’s HTTP AUTH auto-negotiation
  • RKRequestAuthenticationTypeHTTPBasic: Force the use of HTTP Basic authentication. This will supress AUTH challenges as RestKit will add an Authorization header establishing login via HTTP basic. This is an optimization that skips the challenge portion of the request.
  • RKRequestAuthenticationTypeOAuth1: Enable the use of OAuth 1.0 authentication. OAuth1ConsumerKey, OAuth1ConsumerSecret, OAuth1AccessToken, and OAuth1AccessTokenSecret must be set.
  • RKRequestAuthenticationTypeOAuth2: Enable the use of OAuth 2.0 authentication. OAuth2AccessToken must be set.

Default: RKRequestAuthenticationTypeNone

Declared In

RKClient.h

baseURL

The base URL all resources are nested underneath. All requests created through the client will their URL built by appending a resourcePath to the baseURL to form a complete URL.

@property (nonatomic, retain) RKURL *baseURL

Discussion

Changing the baseURL has the side-effect of causing the requestCache instance to be rebuilt. Caches are maintained a per-host basis.

Declared In

RKClient.h

cache

An instance of the request cache used to store/load cacheable responses for requests sent through this client

@property (nonatomic, retain) RKRequestCache *cache

Discussion

Bug: DEPRECATED in v0.10.0: Use requestCache instead.

Declared In

RKClient.h

cachePath

The path used to store response data for this client’s request cache.

@property (nonatomic, readonly) NSString *cachePath

Discussion

The path that is used is the device’s cache directory with RKClientRequestCache-host appended.

Declared In

RKClient.h

cachePolicy

The default cache policy to apply for all requests sent through this client

@property (nonatomic, assign) RKRequestCachePolicy cachePolicy

Discussion

This must be assigned one of the following:

  • RKRequestCachePolicyNone: Never use the cache.
  • RKRequestCachePolicyLoadIfOffline: Load from the cache when offline.
  • RKRequestCachePolicyLoadOnError: Load from the cache if an error is encountered.
  • RKRequestCachePolicyEtag: Load from the cache if there is data stored and the server returns a 304 (Not Modified) response.
  • RKRequestCachePolicyEnabled: Load from the cache whenever data has been stored.
  • RKRequestCachePolicyTimeout: Load from the cache if the cacheTimeoutInterval is reached before the server responds.

See Also

Declared In

RKClient.h

cacheTimeoutInterval

The timeout interval within which the requests should not be sent and the cached response should be used.

@property (nonatomic, assign) NSTimeInterval cacheTimeoutInterval

Discussion

This is only used if the cache policy includes RKRequestCachePolicyTimeout.

Declared In

RKClient.h

defaultHTTPEncoding

The default value used to decode HTTP body content when HTTP headers received do not provide information on the content. This encoding will be used by the RKResponse when creating the body content

@property (nonatomic, assign) NSStringEncoding defaultHTTPEncoding

Declared In

RKClient.h

disableCertificateValidation

Flag for disabling SSL certificate validation.

@property (nonatomic, assign) BOOL disableCertificateValidation

Discussion

Default: NO

Warning: WARNING: This is a potential security exposure and should be used ONLY while debugging in a controlled environment.

Declared In

RKClient.h

password

The password to use for authentication via HTTP AUTH.

@property (nonatomic, retain) NSString *password

Discussion

Used to respond to an authentication challenge when authenticationType is RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.

Declared In

RKClient.h

reachabilityObserver

An instance of RKReachabilityObserver used for determining the availability of network access.

@property (nonatomic, retain) RKReachabilityObserver *reachabilityObserver

Discussion

Initialized using [RKReachabilityObserver reachabilityObserverForInternet] to monitor connectivity to the Internet. Can be changed to directly monitor a remote hostname/IP address or the local WiFi interface instead.

Warning: WARNING: Changing the reachability observer has the side-effect of temporarily suspending the requestQueue until reachability to the new host can be established.

Declared In

RKClient.h

requestCache

An instance of the request cache used to store/load cacheable responses for requests sent through this client

@property (nonatomic, retain) RKRequestCache *requestCache

Declared In

RKClient.h

requestQueue

The request queue to push asynchronous requests onto.

@property (nonatomic, retain) RKRequestQueue *requestQueue

Discussion

Default: A new request queue is instantiated for you during init.

Declared In

RKClient.h

runLoopMode

The run loop mode under which the underlying NSURLConnection is performed

@property (nonatomic, copy) NSString *runLoopMode

Discussion

Default: NSRunLoopCommonModes

Declared In

RKClient.h

serviceUnavailableAlertEnabled

Flag that determines whether the Service Unavailable alert is shown in response to a ServiceUnavailable (503) response.

@property (nonatomic, assign) BOOL serviceUnavailableAlertEnabled

Discussion

Default: NO

Declared In

RKClient.h

serviceUnavailableAlertMessage

The message to use in the alert shown when a request encounters a ServiceUnavailable (503) response.

@property (nonatomic, retain) NSString *serviceUnavailableAlertMessage

Discussion

Default: “The remote resource is unavailable. Please try again later.”

Declared In

RKClient.h

serviceUnavailableAlertTitle

The title to use in the alert shown when a request encounters a ServiceUnavailable (503) response.

@property (nonatomic, retain) NSString *serviceUnavailableAlertTitle

Discussion

Default: “Service Unavailable”

Declared In

RKClient.h

timeoutInterval

An optional timeout interval within which the request should be cancelled.

@property (nonatomic, assign) NSTimeInterval timeoutInterval

Discussion

This is passed along to RKRequest if set. If it isn’t set, it will default to RKRequest’s default timeoutInterval.

Default: Falls through to RKRequest’s timeoutInterval

Declared In

RKClient.h

username

The username to use for authentication via HTTP AUTH.

@property (nonatomic, retain) NSString *username

Discussion

Used to respond to an authentication challenge when authenticationType is RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.

Declared In

RKClient.h

Class Methods

clientWithBaseURL:

Returns a client scoped to a particular base URL.

+ (RKClient *)clientWithBaseURL:(NSURL *)baseURL

Parameters

baseURL

The baseURL to set for the client. All requests will be relative to this base URL.

Return Value

A configured RKClient instance ready to send requests

Discussion

If the singleton client is nil, the return client is set as the singleton.

Declared In

RKClient.h

clientWithBaseURL:username:password:

Returns a Rest client scoped to a particular base URL with a set of HTTP AUTH credentials.

+ (RKClient *)clientWithBaseURL:(NSString *)baseURL username:(NSString *)username password:(NSString *)password

Parameters

baseURL

The baseURL to set for the client. All requests will be relative to this base URL.

username

The username to use for HTTP Authentication challenges

password

The password to use for HTTP Authentication challenges

Return Value

A configured RKClient instance ready to send requests

Discussion

If the singleton client is nil, the return client is set as the singleton.

Bug: DEPRECATED in version 0.9.4: Use [RKClient clientWithBaseURLString:] and set username and password afterwards.

Declared In

RKClient.h

clientWithBaseURLString:

Returns a client scoped to a particular base URL.

+ (RKClient *)clientWithBaseURLString:(NSString *)baseURLString

Parameters

baseURLString

The string to use to construct the NSURL to set the baseURL. All requests will be relative to this base URL.

Return Value

A configured RKClient instance ready to send requests

Discussion

If the singleton client is nil, the return client is set as the singleton.

Declared In

RKClient.h

setSharedClient:

Sets the shared instance of the client, releasing the current instance (if any)

+ (void)setSharedClient:(RKClient *)client

Parameters

client

An RKClient instance to configure as the new shared instance

Declared In

RKClient.h

sharedClient

Returns the shared instance of the client

+ (RKClient *)sharedClient

Declared In

RKClient.h

Instance Methods

URLForResourcePath:

Returns a NSURL by adding a resource path to the base URL

- (NSURL *)URLForResourcePath:(NSString *)resourcePath

Parameters

resourcePath

The resource path to build a URL against

Return Value

An NSURL constructed by concatenating the baseURL and the resourcePath

Discussion

Bug: DEPRECATED in v0.10.0: Use [RKURL URLByAppendingResourcePath:]

Declared In

RKClient.h

URLForResourcePath:queryParams:

Returns a NSURL by adding a resource path to the base URL and appending a URL encoded set of query parameters

- (NSURL *)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary *)queryParams

Parameters

resourcePath

The resource path to append the query parameters onto

queryParams

A dictionary of query parameters to be URL encoded and appended to the resource path.

Return Value

A URL constructed by concatenating the baseURL and the resourcePath with the query parameters appended.

Discussion

This is a convenience method for constructing a new resource path that includes a query. For example, when given a resourcePath of /contacts and a dictionary of parameters containing foo=bar and color=red, will return /contacts?foo=bar&color=red

Warning: NOTE: Assumes that the resource path does not already contain any query parameters.

Declared In

RKClient.h

URLPathForResourcePath:

Returns an NSString by adding a resource path to the base URL

- (NSString *)URLPathForResourcePath:(NSString *)resourcePath

Parameters

resourcePath

The resource path to build a URL against

Return Value

A string URL constructed by concatenating the baseURL and the resourcePath.

Discussion

Bug: DEPRECATED: Use [[RKURL URLByAppendingResourcePath:]](../Classes/RKURL.html#//api/name/URLByAppendingResourcePath:) absoluteString

Declared In

RKClient.h

addRootCertificate:

Adds an additional certificate that will be used to evaluate server SSL certs.

- (void)addRootCertificate:(SecCertificateRef)cert

Parameters

cert

The SecCertificateRef to add to the list of additional SSL certs.

Declared In

RKClient.h

configureRequest:

Configure a request before it is utilized

- (void)configureRequest:(RKRequest *)request

Parameters

request

A request object being configured for dispatch

Declared In

RKConfigurationDelegate.h

delete:delegate:

Destroy a resource via an HTTP DELETE.

- (RKRequest *)delete:(NSString *)resourcePath delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resourcePath to target the request at

delegate

A delegate object to inform of the results

Return Value

The RKRequest object built and sent to the remote system

Declared In

RKClient.h

delete:usingBlock:

Destroys a resource via an HTTP DELETE after executing a given a block using the configured request object.

- (void)delete:(NSString *)resourcePath usingBlock:(void ( ^ ) ( RKRequest *request ))block

Parameters

resourcePath

The resourcePath to target the request at

block

The block to execute with the request before sending it for processing.

Declared In

RKClient.h

get:delegate:

Perform an asynchronous GET request for a resource and inform a delegate of the results.

- (RKRequest *)get:(NSString *)resourcePath delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resourcePath to target the request at

delegate

A delegate object to inform of the results

Return Value

The RKRequest object built and sent to the remote system

Declared In

RKClient.h

get:queryParameters:delegate:

Fetch a resource via an HTTP GET with a dictionary of params.

- (RKRequest *)get:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resourcePath to target the request at

queryParameters

A dictionary of query parameters to append to the resourcePath. Assumes that resourcePath does not contain a query string.

delegate

A delegate object to inform of the results

Return Value

The RKRequest object built and sent to the remote system

Discussion

This request only allows NSDictionary objects as the params. The dictionary will be coerced into a URL encoded string and then appended to the resourcePath as the query string of the request.

Declared In

RKClient.h

get:usingBlock:

Fetches a resource via an HTTP GET after executing a given a block using the configured request object.

- (void)get:(NSString *)resourcePath usingBlock:(void ( ^ ) ( RKRequest *request ))block

Parameters

resourcePath

The resourcePath to target the request at

block

The block to execute with the request before sending it for processing.

Declared In

RKClient.h

initWithBaseURL:

Returns a client scoped to a particular base URL. If the singleton client is nil, the return client is set as the singleton.

- (id)initWithBaseURL:(NSURL *)baseURL

Parameters

baseURL

The baseURL to set for the client. All requests will be relative to this base URL.

Return Value

A configured RKClient instance ready to send requests

Declared In

RKClient.h

initWithBaseURLString:

Returns a client scoped to a particular base URL. If the singleton client is nil, the return client is set as the singleton.

- (id)initWithBaseURLString:(NSString *)baseURLString

Parameters

baseURLString

The string to use to construct the NSURL to set the baseURL. All requests will be relative to this base URL.

Return Value

A configured RKClient instance ready to send requests

Declared In

RKClient.h

isNetworkAvailable

Convenience method for returning the current reachability status from the reachabilityObserver.

- (BOOL)isNetworkAvailable

Return Value

YES if the remote host is accessible

Discussion

Bug: DEPRECATED in v0.10.0: Use [RKClient isNetworkReachable]

Declared In

RKClient.h

isNetworkReachable

Convenience method for returning the current reachability status from the reachabilityObserver.

- (BOOL)isNetworkReachable

Return Value

YES if the remote host is accessible

Discussion

Equivalent to executing [RKClient isNetworkReachable] on the sharedClient

Declared In

RKClient.h

post:params:delegate:

Create a resource via an HTTP POST with a set of form parameters.

- (RKRequest *)post:(NSString *)resourcePath params:(NSObject<RKRequestSerializable> *)params delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resourcePath to target the request at

params

A RKRequestSerializable object to use as the body of the request

delegate

A delegate object to inform of the results

Return Value

The RKRequest object built and sent to the remote system

Discussion

The form parameters passed here must conform to RKRequestSerializable, such as an instance of RKParams.

Declared In

RKClient.h

post:usingBlock:

Creates a resource via an HTTP POST after executing a given a block using the configured request object.

- (void)post:(NSString *)resourcePath usingBlock:(void ( ^ ) ( RKRequest *request ))block

Parameters

resourcePath

The resourcePath to target the request at

block

The block to execute with the request before sending it for processing.

Declared In

RKClient.h

put:params:delegate:

Update a resource via an HTTP PUT.

- (RKRequest *)put:(NSString *)resourcePath params:(NSObject<RKRequestSerializable> *)params delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resourcePath to target the request at

params

A RKRequestSerializable object to use as the body of the request

delegate

A delegate object to inform of the results

Return Value

The RKRequest object built and sent to the remote system

Discussion

The form parameters passed here must conform to RKRequestSerializable, such as an instance of RKParams.

Declared In

RKClient.h

put:usingBlock:

Updates a resource via an HTTP PUT after executing a given a block using the configured request object.

- (void)put:(NSString *)resourcePath usingBlock:(void ( ^ ) ( RKRequest *request ))block

Parameters

resourcePath

The resourcePath to target the request at

block

The block to execute with the request before sending it for processing.

Declared In

RKClient.h

requestWithResourcePath:

Return a request object targeted at a resource path relative to the base URL.

- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath

Parameters

resourcePath

The resource path to configure the request for.

Return Value

A fully configured RKRequest instance ready for sending.

Discussion

By default the method is set to GET. All headers set on the client will automatically be applied to the request as well.

Declared In

RKClient.h

requestWithResourcePath:delegate:

Return a request object targetted at a resource path relative to the base URL.

- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObject<RKRequestDelegate> *)delegate

Parameters

resourcePath

The resource path to configure the request for.

delegate

A delegate to inform of events in the request lifecycle.

Return Value

A fully configured RKRequest instance ready for sending.

Discussion

By default the method is set to GET. All headers set on the client will automatically be applied to the request as well.

Bug: DEPRECATED in v0.10.0: Use [RKClient requestWithResourcePath:] instead.

Declared In

RKClient.h

resourcePath:withQueryParams:

Returns a resource path with a dictionary of query parameters URL encoded and appended

- (NSString *)resourcePath:(NSString *)resourcePath withQueryParams:(NSDictionary *)queryParams

Parameters

resourcePath

The resource path to append the query parameters onto

queryParams

A dictionary of query parameters to be URL encoded and appended to the resource path.

Return Value

A new resource path with the query parameters appended

Discussion

This is a convenience method for constructing a new resource path that includes a query. For example, when given a resourcePath of /contacts and a dictionary of parameters containing foo=bar and color=red, will return /contacts?foo=bar&color=red

Warning: NOTE: This assumes that the resource path does not already contain any query parameters.

Declared In

RKClient.h

setValue:forHTTPHeaderField:

Adds an HTTP header to each request dispatched through the client

- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)header

Parameters

value

The string value to set for the HTTP header

header

The HTTP header to add

Declared In

RKClient.h