Integrated support for configuring runLoopMode on a per request basis. closes #560

This commit is contained in:
Blake Watters
2012-04-17 21:28:48 -04:00
parent ea100b6aac
commit 4071fa9a32
6 changed files with 315 additions and 264 deletions

View File

@@ -4,13 +4,13 @@
//
// Created by Blake Watters on 7/28/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,16 +33,16 @@
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
@@ -50,45 +50,45 @@
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.
@see RKRequest
@see RKResponse
@see RKRequestQueue
@@ -116,7 +116,8 @@
NSMutableSet *_additionalRootCertificates;
BOOL _disableCertificateValidation;
NSStringEncoding _defaultHTTPEncoding;
NSString *_runLoopMode;
// Queue suspension flags
BOOL _awaitingReachabilityDetermination;
}
@@ -128,7 +129,7 @@
/**
Returns a client scoped to a particular base URL.
If the singleton client is nil, the return client is set as the singleton.
@see baseURL
@@ -140,9 +141,9 @@
/**
Returns a client scoped to a particular base URL.
If the singleton client is nil, the return client is set as the singleton.
@see baseURL
@param baseURLString The string to use to construct the NSURL to set the
baseURL. All requests will be relative to this base URL.
@@ -152,10 +153,10 @@
/**
Returns a Rest client scoped to a particular base URL with a set of HTTP AUTH
credentials.
credentials.
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.
@param baseURL The baseURL to set for the client. All requests will be relative
@@ -169,7 +170,7 @@
/**
Returns a client scoped to a particular base URL. If the singleton client is
nil, the return client is set as the singleton.
@see baseURL
@param baseURL The baseURL to set for the client. All requests will be relative
to this base URL.
@@ -180,7 +181,7 @@
/**
Returns a client scoped to a particular base URL. If the singleton client is
nil, the return client is set as the singleton.
@see baseURL
@param baseURLString The string to use to construct the NSURL to set the
baseURL. All requests will be relative to this base URL.
@@ -197,10 +198,10 @@
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.
Changing the baseURL has the side-effect of causing the requestCache instance
to be rebuilt. Caches are maintained a per-host basis.
@see requestCache
*/
@property (nonatomic, retain) RKURL *baseURL;
@@ -212,21 +213,29 @@
/**
An optional timeout interval within which the request should be cancelled.
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
*/
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
/**
The request queue to push asynchronous requests onto.
*Default*: A new request queue is instantiated for you during init.
*/
@property (nonatomic, retain) RKRequestQueue *requestQueue;
/**
The run loop mode under which the underlying NSURLConnection is performed
*Default*: NSRunLoopCommonModes
*/
@property (nonatomic, copy) NSString *runLoopMode;
/**
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
@@ -235,7 +244,7 @@
/**
Adds an HTTP header to each request dispatched through the client
@param value The string value to set for the HTTP header
@param header The HTTP header to add
@see HTTPHeaders
@@ -249,9 +258,9 @@
/**
Flag for disabling SSL certificate validation.
*Default*: NO
@warning **WARNING**: This is a potential security exposure and should be used
**ONLY while debugging** in a controlled environment.
*/
@@ -266,7 +275,7 @@
/**
Adds an additional certificate that will be used to evaluate server SSL certs.
@param cert The SecCertificateRef to add to the list of additional SSL certs.
@see additionalRootCertificates
*/
@@ -279,9 +288,9 @@
/**
The type of authentication to use for this request.
This must be assigned one of the following:
- `RKRequestAuthenticationTypeNone`: Disable the use of authentication
- `RKRequestAuthenticationTypeHTTP`: Use NSURLConnection's HTTP AUTH
auto-negotiation
@@ -294,7 +303,7 @@
and OAuth1AccessTokenSecret must be set.
- `RKRequestAuthenticationTypeOAuth2`: Enable the use of OAuth 2.0
authentication. OAuth2AccessToken must be set.
**Default**: RKRequestAuthenticationTypeNone
*/
@@ -302,20 +311,20 @@
/**
The username to use for authentication via HTTP AUTH.
Used to respond to an authentication challenge when authenticationType is
RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.
@see authenticationType
*/
@property (nonatomic, retain) NSString *username;
/**
The password to use for authentication via HTTP AUTH.
Used to respond to an authentication challenge when authenticationType is
RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.
@see authenticationType
*/
@property (nonatomic, retain) NSString *password;
@@ -327,40 +336,40 @@
/**
The OAuth 1.0 consumer key
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1ConsumerKey;
/**
The OAuth 1.0 consumer secret
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1ConsumerSecret;
/**
The OAuth 1.0 access token
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1AccessToken;
/**
The OAuth 1.0 access token secret
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1AccessTokenSecret;
@@ -372,23 +381,23 @@
/**
The OAuth 2.0 access token
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth2
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth2AccessToken;
/**
The OAuth 2.0 refresh token
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.
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth2RefreshToken;
@@ -398,17 +407,17 @@
///-----------------------------------------------------------------------------
/**
An instance of RKReachabilityObserver used for determining the availability of
An instance of RKReachabilityObserver used for determining the availability of
network access.
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.
@see RKReachabilityObserver
*/
@property (nonatomic, retain) RKReachabilityObserver *reachabilityObserver;
@@ -416,7 +425,7 @@
/**
The title to use in the alert shown when a request encounters a
ServiceUnavailable (503) response.
*Default*: _"Service Unavailable"_
*/
@property (nonatomic, retain) NSString *serviceUnavailableAlertTitle;
@@ -424,7 +433,7 @@
/**
The message to use in the alert shown when a request encounters a
ServiceUnavailable (503) response.
*Default*: _"The remote resource is unavailable. Please try again later."_
*/
@property (nonatomic, retain) NSString *serviceUnavailableAlertMessage;
@@ -432,7 +441,7 @@
/**
Flag that determines whether the Service Unavailable alert is shown in response
to a ServiceUnavailable (503) response.
*Default*: _NO_
*/
@property (nonatomic, assign) BOOL serviceUnavailableAlertEnabled;
@@ -445,9 +454,9 @@
/**
Convenience method for returning the current reachability status from the
reachabilityObserver.
Equivalent to executing `[RKClient isNetworkReachable]` on the sharedClient
@see RKReachabilityObserver
@return YES if the remote host is accessible
*/
@@ -456,7 +465,7 @@
/**
Convenience method for returning the current reachability status from the
reachabilityObserver.
@bug **DEPRECATED** in v0.9.4: Use [RKClient isNetworkReachable]
@see RKReachabilityObserver
@return YES if the remote host is accessible
@@ -471,7 +480,7 @@
/**
An instance of the request cache used to store/load cacheable responses for
requests sent through this client
@bug **DEPRECATED** in v0.9.4: Use requestCache instead.
*/
@property (nonatomic, retain) RKRequestCache *cache DEPRECATED_ATTRIBUTE;
@@ -485,7 +494,7 @@
/**
The timeout interval within which the requests should not be sent and the
cached response should be used.
This is only used if the cache policy includes RKRequestCachePolicyTimeout.
*/
@property (nonatomic, assign) NSTimeInterval cacheTimeoutInterval;
@@ -494,7 +503,7 @@
The default cache policy to apply for all requests sent through this client
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
@@ -505,14 +514,14 @@
stored.
- `RKRequestCachePolicyTimeout`: Load from the cache if the
cacheTimeoutInterval is reached before the server responds.
@see RKRequest
*/
@property (nonatomic, assign) RKRequestCachePolicy cachePolicy;
/**
The path used to store response data for this client's request cache.
The path that is used is the device's cache directory with
`RKClientRequestCache-host` appended.
*/
@@ -530,7 +539,7 @@
/**
Sets the shared instance of the client, releasing the current instance (if any)
@param client An RKClient instance to configure as the new shared instance
*/
+ (void)setSharedClient:(RKClient *)client;
@@ -542,10 +551,10 @@
/**
Return a request object targetted at a resource path relative to the base URL.
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.9.4: Use [RKClient requestWithResourcePath:] instead.
@param resourcePath The resource path to configure the request for.
@param delegate A delegate to inform of events in the request lifecycle.
@@ -556,10 +565,10 @@
/**
Return a request object targeted at a resource path relative to the base URL.
By default the method is set to GET. All headers set on the client will
automatically be applied to the request as well.
@param resourcePath The resource path to configure the request for.
@return A fully configured RKRequest instance ready for sending.
@see RKRequestDelegate
@@ -574,7 +583,7 @@
/**
Perform an asynchronous GET request for a resource and inform a delegate of the
results.
@param resourcePath The resourcePath to target the request at
@param delegate A delegate object to inform of the results
@return The RKRequest object built and sent to the remote system
@@ -583,11 +592,11 @@
/**
Fetch a resource via an HTTP GET with a dictionary of params.
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.
@param resourcePath The resourcePath to target the request at
@param queryParameters A dictionary of query parameters to append to the
resourcePath. Assumes that resourcePath does not contain a query string.
@@ -598,7 +607,7 @@
/**
Fetches a resource via an HTTP GET after executing a given a block using the configured request object.
@param resourcePath The resourcePath to target the request at
@param block The block to execute with the request before sending it for processing.
*/
@@ -606,10 +615,10 @@
/**
Create a resource via an HTTP POST with a set of form parameters.
The form parameters passed here must conform to RKRequestSerializable, such as
an instance of RKParams.
@see RKParams
@param resourcePath The resourcePath to target the request at
@param params A RKRequestSerializable object to use as the body of the request
@@ -621,7 +630,7 @@
/**
Creates a resource via an HTTP POST after executing a given a block using the configured request object.
@param resourcePath The resourcePath to target the request at
@param block The block to execute with the request before sending it for processing.
*/
@@ -632,9 +641,9 @@
The form parameters passed here must conform to RKRequestSerializable, such as
an instance of RKParams.
@see RKParams
@param resourcePath The resourcePath to target the request at
@param params A RKRequestSerializable object to use as the body of the request
@param delegate A delegate object to inform of the results
@@ -645,7 +654,7 @@
/**
Updates a resource via an HTTP PUT after executing a given a block using the configured request object.
@param resourcePath The resourcePath to target the request at
@param block The block to execute with the request before sending it for processing.
*/
@@ -653,7 +662,7 @@
/**
Destroy a resource via an HTTP DELETE.
@param resourcePath The resourcePath to target the request at
@param delegate A delegate object to inform of the results
@return The RKRequest object built and sent to the remote system
@@ -662,7 +671,7 @@
/**
Destroys a resource via an HTTP DELETE after executing a given a block using the configured request object.
@param resourcePath The resourcePath to target the request at
@param block The block to execute with the request before sending it for processing.
*/
@@ -674,9 +683,9 @@
/**
Returns a NSURL by adding a resource path to the base URL
@bug **DEPRECATED** in v0.9.4: Use [RKURL URLByAppendingResourcePath:]
@param resourcePath The resource path to build a URL against
@return An NSURL constructed by concatenating the baseURL and the resourcePath
*/
@@ -684,9 +693,9 @@
/**
Returns an NSString by adding a resource path to the base URL
@bug **DEPRECATED**: Use `[RKURL URLByAppendingResourcePath:] absoluteString`
@param resourcePath The resource path to build a URL against
@return A string URL constructed by concatenating the baseURL and the
resourcePath.
@@ -696,17 +705,17 @@
/**
Returns a resource path with a dictionary of query parameters URL encoded and
appended
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.
@bug **DEPRECATED**: Use [RKURL URLByAppendingQueryParameters:]
@param resourcePath The resource path to append the query parameters onto
@param queryParams A dictionary of query parameters to be URL encoded and
appended to the resource path.
@@ -717,17 +726,17 @@
/**
Returns a NSURL by adding a resource path to the base URL and appending a URL
encoded set of query parameters
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.
@bug **DEPRECATED**: Use [RKURL URLByAppendingResourcePath:queryParameters:]
@param resourcePath The resource path to append the query parameters onto
@param queryParams A dictionary of query parameters to be URL encoded and
appended to the resource path.
@@ -746,9 +755,9 @@
/**
Returns an NSURL with the specified resource path appended to the base URL that
the shared RKClient instance is configured with.
Shortcut for calling `[[RKClient sharedClient] URLForResourcePath:@"/some/path"]`
@bug **DEPRECATED** in v0.9.4: Use [[RKClient sharedClient].baseURL
URLByAppendingResourcePath:]
@param resourcePath The resource path to append to the baseURL of the
@@ -761,10 +770,10 @@ NSURL *RKMakeURL(NSString *resourcePath) DEPRECATED_ATTRIBUTE;
/**
Returns an NSString with the specified resource path appended to the base URL
that the shared RKClient instance is configured with
Shortcut for calling
`[[RKClient sharedClient] URLPathForResourcePath:@"/some/path"]`
@bug **DEPRECATED** in v0.9.4: Use
[[[RKClient sharedClient].baseURL URLByAppendingResourcePath:] absoluteString]
@param resourcePath The resource path to append to the baseURL of the
@@ -780,15 +789,15 @@ NSString *RKMakeURLPath(NSString *resourcePath) DEPRECATED_ATTRIBUTE;
values of the properties specified and returns the generated path. Defaults to
adding escapes. If desired, turn them off with
RKMakePathWithObjectAddingEscapes.
For example, given an 'article' object with an 'articleID' property of 12345
and a 'name' of Blake, RKMakePathWithObject(@"articles/:articleID/:name", article)
would generate @"articles/12345/Blake"
This functionality is the basis for resource path generation in the Router.
@bug **DEPRECATED** in v0.9.4: Use [NSString interpolateWithObject:]
@param path The colon encoded path pattern string to use for interpolation.
@param object The object containing the properties needed for interpolation.
@return A new path string, replacing the pattern's parameters with the object's
@@ -801,13 +810,13 @@ NSString *RKMakePathWithObject(NSString *path, id object) DEPRECATED_ATTRIBUTE;
Convenience method for generating a path against the properties of an object. Takes
a string with property names encoded with colons and interpolates the values of
the properties specified and returns the generated path.
For example, given an 'article' object with an 'articleID' property of 12345
and a 'code' of "This/That", `RKMakePathWithObjectAddingEscapes(@"articles/:articleID/:code", article, YES)`
would generate @"articles/12345/This%2FThat"
This functionality is the basis for resource path generation in the Router.
@bug **DEPRECATED** in v0.9.4: Use [NSString interpolateWithObject:addingEscapes:]
@param path The colon encoded path pattern string to use for interpolation.
@param object The object containing the properties needed for interpolation.
@@ -821,18 +830,18 @@ NSString *RKMakePathWithObjectAddingEscapes(NSString *pattern, id object, BOOL a
/**
Returns a resource path with a dictionary of query parameters URL encoded and
appended.
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 This assumes that the resource path does not already contain any query
parameters.
@bug **DEPRECATED** in v0.9.4: Use [NSString stringByAppendingQueryParameters:]
instead
@param resourcePath The resource path to append the query parameters onto
@param queryParams A dictionary of query parameters to be URL encoded and
appended to the resource path.

View File

@@ -4,13 +4,13 @@
//
// Created by Blake Watters on 7/28/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -90,6 +90,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
@synthesize timeoutInterval = _timeoutInterval;
@synthesize defaultHTTPEncoding = _defaultHTTPEncoding;
@synthesize cacheTimeoutInterval = _cacheTimeoutInterval;
@synthesize runLoopMode = _runLoopMode;
+ (RKClient *)sharedClient {
return sharedClient;
@@ -124,18 +125,19 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
_additionalRootCertificates = [[NSMutableSet alloc] init];
_defaultHTTPEncoding = NSUTF8StringEncoding;
self.cacheTimeoutInterval = 0;
self.runLoopMode = NSRunLoopCommonModes;
self.serviceUnavailableAlertEnabled = NO;
self.serviceUnavailableAlertTitle = NSLocalizedString(@"Service Unavailable", nil);
self.serviceUnavailableAlertMessage = NSLocalizedString(@"The remote resource is unavailable. Please try again later.", nil);
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(serviceDidBecomeUnavailableNotification:)
name:RKServiceDidBecomeUnavailableNotification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(serviceDidBecomeUnavailableNotification:)
name:RKServiceDidBecomeUnavailableNotification
object:nil];
// Configure reachability and queue
[self addObserver:self forKeyPath:@"reachabilityObserver" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
self.requestQueue = [RKRequestQueue requestQueue];
[self addObserver:self forKeyPath:@"baseURL" options:NSKeyValueObservingOptionNew context:nil];
[self addObserver:self forKeyPath:@"requestQueue" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
@@ -145,18 +147,18 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
- (id)initWithBaseURL:(NSURL *)baseURL {
self = [self init];
if (self) {
if (self) {
self.cachePolicy = RKRequestCachePolicyDefault;
self.baseURL = [RKURL URLWithBaseURL:baseURL];
if (sharedClient == nil) {
[RKClient setSharedClient:self];
// Initialize Logging as soon as a client is created
RKLogInitialize();
}
}
return self;
}
@@ -164,28 +166,29 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
return [self initWithBaseURL:[RKURL URLWithString:baseURLString]];
}
- (void)dealloc {
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Allow KVO to fire
self.reachabilityObserver = nil;
self.baseURL = nil;
self.requestQueue = nil;
[self removeObserver:self forKeyPath:@"reachabilityObserver"];
[self removeObserver:self forKeyPath:@"baseURL"];
[self removeObserver:self forKeyPath:@"requestQueue"];
self.username = nil;
self.password = nil;
self.serviceUnavailableAlertTitle = nil;
self.serviceUnavailableAlertMessage = nil;
self.requestCache = nil;
self.runLoopMode = nil;
[_HTTPHeaders release];
[_additionalRootCertificates release];
if (sharedClient == self) sharedClient = nil;
[super dealloc];
}
@@ -201,7 +204,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
if (self.reachabilityObserver) {
isNetworkReachable = [self.reachabilityObserver isNetworkReachable];
}
return isNetworkReachable;
}
@@ -215,20 +218,21 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
request.queue = self.requestQueue;
request.reachabilityObserver = self.reachabilityObserver;
request.defaultHTTPEncoding = self.defaultHTTPEncoding;
request.additionalRootCertificates = self.additionalRootCertificates;
request.disableCertificateValidation = self.disableCertificateValidation;
request.runLoopMode = self.runLoopMode;
// If a timeoutInterval was set on the client, we'll pass it on to the request.
// Otherwise, we'll let the request default to its own timeout interval.
if (self.timeoutInterval) {
request.timeoutInterval = self.timeoutInterval;
}
if (self.cacheTimeoutInterval) {
request.cacheTimeoutInterval = self.cacheTimeoutInterval;
}
// OAuth 1 Parameters
request.OAuth1AccessToken = self.OAuth1AccessToken;
request.OAuth1AccessTokenSecret = self.OAuth1AccessTokenSecret;
@@ -251,31 +255,31 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
- (void)reachabilityObserverDidChange:(NSDictionary *)change {
RKReachabilityObserver *oldReachabilityObserver = [change objectForKey:NSKeyValueChangeOldKey];
RKReachabilityObserver *newReachabilityObserver = [change objectForKey:NSKeyValueChangeNewKey];
if (! [oldReachabilityObserver isEqual:[NSNull null]]) {
RKLogDebug(@"Reachability observer changed for RKClient %@, disposing of previous instance: %@", self, oldReachabilityObserver);
// Cleanup if changed immediately after client init
[[NSNotificationCenter defaultCenter] removeObserver:self name:RKReachabilityWasDeterminedNotification object:oldReachabilityObserver];
}
if (! [newReachabilityObserver isEqual:[NSNull null]]) {
// Suspend the queue until reachability to our new hostname is established
if (! [newReachabilityObserver isReachabilityDetermined]) {
self.requestQueue.suspended = YES;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityWasDetermined:)
name:RKReachabilityWasDeterminedNotification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityWasDetermined:)
name:RKReachabilityWasDeterminedNotification
object:newReachabilityObserver];
RKLogDebug(@"Reachability observer changed for client %@, suspending queue %@ until reachability to host '%@' can be determined",
RKLogDebug(@"Reachability observer changed for client %@, suspending queue %@ until reachability to host '%@' can be determined",
self, self.requestQueue, newReachabilityObserver.host);
// Maintain a flag for Reachability determination status. This ensures that we can do the right thing in the
// event that the requestQueue is changed while we are in an inderminate suspension state
_awaitingReachabilityDetermination = YES;
} else {
self.requestQueue.suspended = NO;
RKLogDebug(@"Reachability observer changed for client %@, unsuspending queue %@ as new observer already has determined reachability to %@",
RKLogDebug(@"Reachability observer changed for client %@, unsuspending queue %@ as new observer already has determined reachability to %@",
self, self.requestQueue, newReachabilityObserver.host);
_awaitingReachabilityDetermination = NO;
}
@@ -284,14 +288,14 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
- (void)baseURLDidChange:(NSDictionary *)change {
RKURL *newBaseURL = [change objectForKey:NSKeyValueChangeNewKey];
// Don't crash if baseURL is nil'd out (i.e. dealloc)
if (! [newBaseURL isEqual:[NSNull null]]) {
// Configure a cache for the new base URL
[_requestCache release];
_requestCache = [[RKRequestCache alloc] initWithPath:[self cachePath]
storagePolicy:RKRequestCacheStoragePolicyPermanently];
// Determine reachability strategy (if user has not already done so)
if (self.reachabilityObserver == nil) {
NSString *hostName = [newBaseURL host];
@@ -308,12 +312,12 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
if (! _awaitingReachabilityDetermination) {
return;
}
// If we are awaiting reachability determination, suspend the new queue
RKRequestQueue *newQueue = [change objectForKey:NSKeyValueChangeNewKey];
if (! [newQueue isEqual:[NSNull null]]) {
// The request queue has changed while we were awaiting reachability.
// The request queue has changed while we were awaiting reachability.
// Suspend the queue until reachability is determined
newQueue.suspended = !self.reachabilityObserver.reachabilityDetermined;
}
@@ -333,14 +337,14 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
RKRequest *request = [[RKRequest alloc] initWithURL:[self.baseURL URLByAppendingResourcePath:resourcePath]];
[self configureRequest:request];
[request autorelease];
return request;
}
- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObject<RKRequestDelegate> *)delegate {
RKRequest *request = [self requestWithResourcePath:resourcePath];
request.delegate = delegate;
return request;
}
@@ -362,7 +366,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
if (method != RKRequestMethodGET) {
request.params = params;
}
[request send];
return request;
@@ -397,7 +401,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar
- (void)reachabilityWasDetermined:(NSNotification *)notification {
RKReachabilityObserver *observer = (RKReachabilityObserver *) [notification object];
NSAssert(observer == self.reachabilityObserver, @"Received unexpected reachability notification from inappropriate reachability observer");
RKLogDebug(@"Reachability to host '%@' determined for client %@, unsuspending queue %@", observer.host, self, self.requestQueue);
_awaitingReachabilityDetermination = NO;
self.requestQueue.suspended = NO;

View File

@@ -4,13 +4,13 @@
//
// Created by Jeremy Ellison on 7/27/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -82,7 +82,7 @@ typedef enum {
#if TARGET_OS_IPHONE
/**
Background Request Policy
On iOS 4.x and higher, UIKit provides support for continuing activities for a
limited amount of time in the background. RestKit provides simple support for
continuing a request when in the background.
@@ -110,7 +110,7 @@ typedef enum RKRequestBackgroundPolicy {
/**
Authentication type for the request
Based on the authentication type that is selected, authentication functionality
is triggered and other options may be required.
*/
@@ -122,10 +122,10 @@ typedef enum {
/**
Use NSURLConnection's HTTP AUTH auto-negotiation
*/
RKRequestAuthenticationTypeHTTP,
RKRequestAuthenticationTypeHTTP,
/**
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.
@@ -133,14 +133,14 @@ typedef enum {
RKRequestAuthenticationTypeHTTPBasic,
/**
Enable the use of OAuth 1.0 authentication.
OAuth1ConsumerKey, OAuth1ConsumerSecret, OAuth1AccessToken, and
OAuth1AccessTokenSecret must be set when using this type.
*/
RKRequestAuthenticationTypeOAuth1,
/**
Enable the use of OAuth 2.0 authentication.
OAuth2AccessToken must be set when using this type.
*/
RKRequestAuthenticationTypeOAuth2
@@ -187,10 +187,11 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
RKReachabilityObserver *_reachabilityObserver;
NSTimer *_timeoutTimer;
NSStringEncoding _defaultHTTPEncoding;
NSSet *_additionalRootCertificates;
BOOL _disableCertificateValidation;
BOOL _followRedirect;
NSString *_runLoopMode;
#if TARGET_OS_IPHONE
RKRequestBackgroundPolicy _backgroundPolicy;
@@ -209,7 +210,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Creates and returns a RKRequest object initialized to load content from a
provided URL.
@param URL The remote URL to load
@return An autoreleased RKRequest object initialized with URL.
*/
@@ -217,7 +218,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Initializes a RKRequest object to load from a provided URL
@param URL The remote URL to load
@return An RKRequest object initialized with URL.
*/
@@ -226,7 +227,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Creates and returns a RKRequest object initialized to load content from a
provided URL with a specified delegate.
@bug **DEPRECATED** in v0.9.4: Use [RKRequest requestWithURL:] instead
@param URL The remote URL to load
@param delegate The delegate that will handle the response callbacks.
@@ -261,16 +262,16 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The HTTP verb in which the request is sent
**Default**: RKRequestMethodGET
*/
@property (nonatomic, assign) RKRequestMethod method;
/**
Returns HTTP method as a string used for this request.
This should be set through the method property using an RKRequestMethod type.
@see [RKRequest method]
*/
@property (nonatomic, readonly) NSString *HTTPMethod;
@@ -286,7 +287,14 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
@property (nonatomic, retain) NSDictionary *additionalHTTPHeaders;
/**
An opaque pointer to associate user defined data with the request.
The run loop mode under which the underlying NSURLConnection is performed
*Default*: NSRunLoopCommonModes
*/
@property (nonatomic, copy) NSString *runLoopMode;
/**
* An opaque pointer to associate user defined data with the request.
*/
@property (nonatomic, retain) id userData;
@@ -309,7 +317,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
Sets the request body using the provided NSDictionary after passing the
NSDictionary through serialization using the currently configured parser for
the provided MIMEType.
@param body An NSDictionary of key/value pairs to be serialized and sent as
the HTTP body.
@param MIMEType The MIMEType for the parser to use for the dictionary.
@@ -318,7 +326,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The HTTP body as a NSData used for this request
*/
*/
@property (nonatomic, retain) NSData *HTTPBody;
/**
@@ -333,7 +341,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The delegate to inform when the request is completed
If the object implements the RKRequestDelegate protocol, it will receive
request lifecycle event messages.
*/
@@ -343,12 +351,12 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
A delegate responsible for configuring the request. Centralizes common
configuration data (such as HTTP headers, authentication information, etc)
for re-use.
RKClient and RKObjectManager conform to the RKConfigurationDelegate protocol.
Request and object loader instances built through these objects will have a
reference to their parent client/object manager assigned as the configuration
delegate.
**Default**: nil
@see RKClient
@see RKObjectManager
@@ -362,14 +370,14 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
A block to invoke when the receiver has loaded a response.
@see [RKRequestDelegate request:didLoadResponse:]
*/
@property (nonatomic, copy) RKRequestDidLoadResponseBlock onDidLoadResponse;
/**
A block to invoke when the receuver has failed loading due to an error.
@see [RKRequestDelegate request:didFailLoadWithError:]
*/
@property (nonatomic, copy) RKRequestDidFailLoadWithErrorBlock onDidFailLoadWithError;
@@ -388,7 +396,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The policy to take on transition to the background (iOS 4.x and higher only)
**Default:** RKRequestBackgroundPolicyCancel
*/
@property (nonatomic, assign) RKRequestBackgroundPolicy backgroundPolicy;
@@ -406,9 +414,9 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The type of authentication to use for this request.
This must be assigned one of the following:
- `RKRequestAuthenticationTypeNone`: Disable the use of authentication
- `RKRequestAuthenticationTypeHTTP`: Use NSURLConnection's HTTP AUTH
auto-negotiation
@@ -421,27 +429,27 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
and OAuth1AccessTokenSecret must be set.
- `RKRequestAuthenticationTypeOAuth2`: Enable the use of OAuth 2.0
authentication. OAuth2AccessToken must be set.
**Default**: RKRequestAuthenticationTypeNone
*/
@property (nonatomic, assign) RKRequestAuthenticationType authenticationType;
/**
The username to use for authentication via HTTP AUTH.
Used to respond to an authentication challenge when authenticationType is
RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.
@see authenticationType
*/
@property (nonatomic, retain) NSString *username;
/**
The password to use for authentication via HTTP AUTH.
Used to respond to an authentication challenge when authenticationType is
RKRequestAuthenticationTypeHTTP or RKRequestAuthenticationTypeHTTPBasic.
@see authenticationType
*/
@property (nonatomic, retain) NSString *password;
@@ -453,40 +461,40 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The OAuth 1.0 consumer key
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1ConsumerKey;
/**
The OAuth 1.0 consumer secret
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1ConsumerSecret;
/**
The OAuth 1.0 access token
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1AccessToken;
/**
The OAuth 1.0 access token secret
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth1
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth1AccessTokenSecret;
@@ -498,10 +506,10 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The OAuth 2.0 access token
Used to build an Authorization header when authenticationType is
RKRequestAuthenticationTypeOAuth2
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth2AccessToken;
@@ -509,13 +517,13 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The OAuth 2.0 refresh token
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.
@see authenticationType
*/
@property (nonatomic, retain) NSString *OAuth2RefreshToken;
@@ -528,7 +536,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Returns the cache key for getting/setting the cache entry for this request in
the cache.
The cacheKey is an MD5 value computed by hashing a combination of the
destination URL, the HTTP verb, and the request body (when possible).
*/
@@ -541,11 +549,11 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The request cache to store and load responses for this request.
Generally configured by the RKClient instance that minted this request
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
@@ -561,7 +569,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Returns YES if the request is cacheable
Only GET requests are considered cacheable (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html).
*/
- (BOOL)isCacheable;
@@ -580,11 +588,11 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Flag for disabling SSL certificate validation.
When YES, SSL certificates will not be validated.
*Default*: NO
@warning **WARNING**: This is a potential security exposure and should be used
**ONLY while debugging** in a controlled environment.
*/
@@ -602,9 +610,9 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
///-----------------------------------------------------------------------------
/**
Setup the NSURLRequest.
The request must be prepared right before dispatching.
@return A boolean for the success of the URL preparation.
*/
- (BOOL)prepareURLRequest;
@@ -627,7 +635,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Send the request synchronously and return a hydrated response object.
@return An RKResponse object with the result of the request.
*/
- (RKResponse *)sendSynchronously;
@@ -641,12 +649,12 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Cancels the underlying URL connection.
This will call the requestDidCancel: delegate method if your delegate responds
to it. This does not subsequently set the the request's delegate to nil.
However, it's good practice to cancel the RKRequest and immediately set the
delegate property to nil within the delegate's dealloc method.
@see NSURLConnection:cancel
*/
- (void)cancel;
@@ -654,7 +662,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The reachability observer to consult for network status. Used for performing
offline cache loads.
Generally configured by the RKClient instance that minted this request.
*/
@property (nonatomic, retain) RKReachabilityObserver *reachabilityObserver;
@@ -677,7 +685,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Callback performed to notify the request that the underlying NSURLConnection
has failed with an error.
@param error An NSError object containing the RKRestKitError that triggered
the callback.
*/
@@ -686,7 +694,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Callback performed to notify the request that the underlying NSURLConnection
has completed with a response.
@param response An RKResponse object with the result of the request.
*/
- (void)didFinishLoad:(RKResponse *)response;
@@ -699,24 +707,24 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
The timeout interval within which the request should be cancelled if no data
has been received.
The timeout timer is cancelled as soon as we start receiving data and are
expecting the request to finish.
**Default**: 120.0 seconds
*/
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
/**
Creates a timeoutTimer to trigger the timeout method
This is mainly used so we can test that the timer is only being created once.
*/
- (void)createTimeoutTimer;
/**
Cancels request due to connection timeout exceeded.
This method is invoked by the timeoutTimer upon its expiration and will return
an RKRequestConnectionTimeoutError via didFailLoadWithError:
*/
@@ -724,7 +732,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Invalidates the timeout timer.
Called by RKResponse when the NSURLConnection begins receiving data.
*/
- (void)invalidateTimeoutTimer;
@@ -776,14 +784,14 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Returns YES when the request was sent to the specified resource path
@param resourcePath A string of the resource path that we want to check against
*/
- (BOOL)wasSentToResourcePath:(NSString *)resourcePath;
/**
Returns YES when the receiver was sent to the specified resource path with a given request method.
@param resourcePath A string of the resource path that we want to check against
@param method The HTTP method to confirm the request was sent with.
*/
@@ -804,7 +812,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Tells the delegate the request is about to be prepared for sending to the remote host.
@param request The RKRequest object that is about to be sent.
*/
- (void)requestWillPrepareForSend:(RKRequest *)request;
@@ -819,14 +827,14 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Sent when a request has started loading
@param request The RKRequest object that has begun loading.
*/
- (void)requestDidStartLoad:(RKRequest *)request;
/**
Sent when a request has uploaded data to the remote site
@param request The RKRequest object that is handling the loading.
@param bytesWritten An integer of the bytes of the chunk just sent to the
remote site.
@@ -839,7 +847,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Sent when request has received data from remote site
@param request The RKRequest object that is handling the loading.
@param bytesReceived An integer of the bytes of the chunk just received from
the remote site.
@@ -857,7 +865,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Sent when a request has finished loading
@param request The RKRequest object that was handling the loading.
@param response The RKResponse object containing the result of the request.
*/
@@ -870,7 +878,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Sent when a request has failed due to an error
@param request The RKRequest object that was handling the loading.
@param error An NSError object containing the RKRestKitError that triggered
the callback.
@@ -879,15 +887,15 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error);
/**
Sent to the delegate when a request was cancelled
@param request The RKRequest object that was cancelled.
*/
- (void)requestDidCancelLoad:(RKRequest *)request;
/**
Sent to the delegate when a request has timed out. This is sent when a
Sent to the delegate when a request has timed out. This is sent when a
backgrounded request expired before completion.
@param request The RKRequest object that timed out.
*/
- (void)requestDidTimeout:(RKRequest *)request;

View File

@@ -4,13 +4,13 @@
//
// Created by Jeremy Ellison on 7/27/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -118,6 +118,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
@synthesize disableCertificateValidation = _disableCertificateValidation;
@synthesize cancelled = _cancelled;
@synthesize followRedirect = _followRedirect;
@synthesize runLoopMode = _runLoopMode;
#if TARGET_OS_IPHONE
@synthesize backgroundPolicy = _backgroundPolicy, backgroundTaskIdentifier = _backgroundTaskIdentifier;
@@ -145,6 +146,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
- (id)init {
self = [super init];
if (self) {
self.runLoopMode = NSRunLoopCommonModes;
#if TARGET_OS_IPHONE
_backgroundPolicy = RKRequestBackgroundPolicyNone;
_backgroundTaskIdentifier = 0;
@@ -194,7 +196,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
self.delegate = nil;
if (_onDidLoadResponse) Block_release(_onDidLoadResponse);
if (_onDidFailLoadWithError) Block_release(_onDidFailLoadWithError);
_delegate = nil;
_configurationDelegate = nil;
[_reachabilityObserver release];
@@ -217,7 +219,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
[_password release];
_password = nil;
[_cache release];
_cache = nil;
_cache = nil;
[_OAuth1ConsumerKey release];
_OAuth1ConsumerKey = nil;
[_OAuth1ConsumerSecret release];
@@ -237,7 +239,9 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
[self invalidateTimeoutTimer];
[_timeoutTimer release];
_timeoutTimer = nil;
[_runLoopMode release];
_runLoopMode = nil;
// Cleanup a background task if there is any
[self cleanupBackgroundTask];
@@ -296,7 +300,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
} else {
[_URLRequest setValue:@"0" forHTTPHeaderField:@"Content-Length"];
}
// Add authentication headers so we don't have to deal with an extra cycle for each message requiring basic auth.
if (self.authenticationType == RKRequestAuthenticationTypeHTTPBasic && _username && _password) {
CFHTTPMessageRef dummyRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self HTTPMethod], (CFURLRef)[self URL], kCFHTTPVersion1_1);
@@ -310,19 +314,19 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
CFRelease(dummyRequest);
}
}
// Add OAuth headers if is need it
// OAuth 1
if(self.authenticationType == RKRequestAuthenticationTypeOAuth1){
if(self.authenticationType == RKRequestAuthenticationTypeOAuth1){
NSURLRequest *echo = nil;
// use the suitable parameters dict
NSDictionary *parameters = nil;
if ([self.params isKindOfClass:[RKParams class]])
parameters = [(RKParams *)self.params dictionaryOfPlainTextParams];
else
else
parameters = [_URL queryParameters];
if (self.method == RKRequestMethodPUT)
echo = [GCOAuth URLRequestForPath:[_URL path]
PUTParameters:parameters
@@ -354,13 +358,13 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
[_URLRequest setValue:[echo valueForHTTPHeaderField:@"Accept-Encoding"] forHTTPHeaderField:@"Accept-Encoding"];
[_URLRequest setValue:[echo valueForHTTPHeaderField:@"User-Agent"] forHTTPHeaderField:@"User-Agent"];
}
// OAuth 2 valid request
if(self.authenticationType == RKRequestAuthenticationTypeOAuth2) {
NSString *authorizationString = [NSString stringWithFormat:@"OAuth2 %@",self.OAuth2AccessToken];
[_URLRequest setValue:authorizationString forHTTPHeaderField:@"Authorization"];
}
if (self.cachePolicy & RKRequestCachePolicyEtag) {
NSString* etag = [self.cache etagForRequest:self];
if (etag) {
@@ -373,17 +377,17 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
// Setup the NSURLRequest. The request must be prepared right before dispatching
- (BOOL)prepareURLRequest {
[_URLRequest setHTTPMethod:[self HTTPMethod]];
if ([self.delegate respondsToSelector:@selector(requestWillPrepareForSend:)]) {
[self.delegate requestWillPrepareForSend:self];
}
[self setRequestBody];
[self addHeadersToRequest];
NSString* body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding];
RKLogTrace(@"Prepared %@ URLRequest '%@'. HTTP Headers: %@. HTTP Body: %@.", [self HTTPMethod], _URLRequest, [_URLRequest allHTTPHeaderFields], body);
[body release];
[body release];
return YES;
}
@@ -449,8 +453,10 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
}
RKResponse* response = [[[RKResponse alloc] initWithRequest:self] autorelease];
_connection = [[NSURLConnection connectionWithRequest:_URLRequest delegate:response] retain];
_connection = [[[[NSURLConnection alloc] initWithRequest:_URLRequest delegate:response startImmediately:NO] autorelease] retain];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:self.runLoopMode];
[_connection start];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestSentNotification object:self userInfo:nil];
}
@@ -478,7 +484,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
if (nil == self.reachabilityObserver || NO == [self.reachabilityObserver isReachabilityDetermined]) {
return YES;
}
return [self.reachabilityObserver isNetworkReachable];
}
@@ -565,7 +571,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
[self didFinishLoad:response];
} else if ([self shouldDispatchRequest]) {
RKLogDebug(@"Sending synchronous %@ request to URL %@.", [self HTTPMethod], [[self URL] absoluteString]);
if (![self prepareURLRequest]) {
// TODO: Logging
return nil;
@@ -580,7 +586,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
_URLRequest.timeoutInterval = _timeoutInterval;
payload = [NSURLConnection sendSynchronousRequest:_URLRequest returningResponse:&URLResponse error:&error];
if (payload != nil) error = nil;
response = [[[RKResponse alloc] initWithSynchronousRequest:self URLResponse:URLResponse body:payload error:error] autorelease];
@@ -648,12 +654,12 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[_delegate request:self didFailLoadWithError:error];
}
if (self.onDidFailLoadWithError) {
self.onDidFailLoadWithError(error);
}
NSDictionary* userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification
object:self
@@ -692,16 +698,16 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
if ([_delegate respondsToSelector:@selector(request:didLoadResponse:)]) {
[_delegate request:self didLoadResponse:finalResponse];
}
if (self.onDidLoadResponse) {
self.onDidLoadResponse(finalResponse);
}
if ([response isServiceUnavailable]) {
[[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self];
}
NSDictionary* userInfo = [NSDictionary dictionaryWithObject:finalResponse
forKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidLoadResponseNotification
@@ -761,7 +767,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
_URLRequest.URL = URL;
}
- (void)setResourcePath:(NSString *)resourcePath {
- (void)setResourcePath:(NSString *)resourcePath {
if ([self.URL isKindOfClass:[RKURL class]]) {
self.URL = [(RKURL *)self.URL URLByReplacingResourcePath:resourcePath];
} else {
@@ -798,7 +804,7 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
if (! [self isCacheable]) {
return nil;
}
// Use [_params HTTPBody] because the URLRequest body may not have been set up yet.
NSString* compositeCacheKey = nil;
if (_params) {
@@ -816,12 +822,12 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) {
- (void)setBody:(NSDictionary *)body forMIMEType:(NSString *)MIMEType {
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType];
NSError *error = nil;
NSString* parsedValue = [parser stringFromObject:body error:&error];
RKLogTrace(@"parser=%@, error=%@, parsedValue=%@", parser, error, parsedValue);
if (error == nil && parsedValue) {
self.params = [RKRequestSerialization serializationWithData:[parsedValue dataUsingEncoding:NSUTF8StringEncoding]
MIMEType:MIMEType];