Merge branch 'reachability-queue-three20' of git://github.com/twotoasters/RestKit into reachability-queue-three20

Conflicts:
	Code/Network/RKRequest.m
	RestKit.xcodeproj/project.pbxproj
This commit is contained in:
Jeff Arena
2010-12-01 21:06:54 -08:00
16 changed files with 381 additions and 264 deletions

View File

@@ -11,3 +11,4 @@
#import "RKResponse.h"
#import "RKRequestSerializable.h"
#import "RKReachabilityObserver.h"
#import "RKRequestQueue.h"

View File

@@ -103,11 +103,13 @@
*/
- (NSURL*)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary*)queryParams;
- (void)setupRequest:(RKRequest*)request;
/**
* 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.
*/
- (RKRequest*)requestWithResourcePath:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)requestWithResourcePath:(NSString*)resourcePath delegate:(id)delegate;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Asynchronous Helper Methods
@@ -120,31 +122,31 @@
*/
/**
* Fetch a resource via an HTTP GET and invoke a callback with the result
* Fetch a resource via an HTTP GET
*/
- (RKRequest*)get:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)get:(NSString*)resourcePath delegate:(id)delegate;
/**
* Fetch a resource via an HTTP GET with a dictionary of params and invoke a callback with the resulting payload
* Fetch a resource via an HTTP GET with a dictionary of params
*
* Note that 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.
*/
- (RKRequest*)get:(NSString*)resourcePath queryParams:(NSDictionary*)queryParams delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)get:(NSString*)resourcePath queryParams:(NSDictionary*)queryParams delegate:(id)delegate;
/**
* Create a resource via an HTTP POST with a set of form parameters and invoke a callback with the resulting payload
* Create a resource via an HTTP POST with a set of form parameters
*/
- (RKRequest*)post:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)post:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate;
/**
* Update a resource via an HTTP PUT and invoke a callback with the resulting payload
* Update a resource via an HTTP PUT
*/
- (RKRequest*)put:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)put:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate;
/**
* Destroy a resource via an HTTP DELETE and invoke a callback with the resulting payload
* Destroy a resource via an HTTP DELETE
*/
- (RKRequest*)delete:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback;
- (RKRequest*)delete:(NSString*)resourcePath delegate:(id)delegate;
@end

View File

@@ -123,8 +123,8 @@ static RKClient* sharedClient = nil;
_baseURLReachabilityObserver = [[RKReachabilityObserver reachabilityObserverWithHostName:baseURL] retain];
}
- (RKRequest*)requestWithResourcePath:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback {
RKRequest* request = [[RKRequest alloc] initWithURL:[self URLForResourcePath:resourcePath] delegate:delegate callback:callback];
- (RKRequest*)requestWithResourcePath:(NSString*)resourcePath delegate:(id)delegate {
RKRequest* request = [[RKRequest alloc] initWithURL:[self URLForResourcePath:resourcePath] delegate:delegate];
[self setupRequest:request];
[request autorelease];
@@ -135,8 +135,8 @@ static RKClient* sharedClient = nil;
// Asynchronous Requests
///////////////////////////////////////////////////////////////////////////////////////////////////////////
- (RKRequest*)load:(NSString*)resourcePath method:(RKRequestMethod)method params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate callback:(SEL)callback {
RKRequest* request = [[RKRequest alloc] initWithURL:[self URLForResourcePath:resourcePath] delegate:delegate callback:callback];
- (RKRequest*)load:(NSString*)resourcePath method:(RKRequestMethod)method params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate {
RKRequest* request = [[RKRequest alloc] initWithURL:[self URLForResourcePath:resourcePath] delegate:delegate];
[self setupRequest:request];
[request autorelease];
request.params = params;
@@ -146,25 +146,25 @@ static RKClient* sharedClient = nil;
return request;
}
- (RKRequest*)get:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback {
return [self load:resourcePath method:RKRequestMethodGET params:nil delegate:delegate callback:callback];
- (RKRequest*)get:(NSString*)resourcePath delegate:(id)delegate {
return [self load:resourcePath method:RKRequestMethodGET params:nil delegate:delegate];
}
- (RKRequest*)get:(NSString*)resourcePath queryParams:(NSDictionary*)queryParams delegate:(id)delegate callback:(SEL)callback {
- (RKRequest*)get:(NSString*)resourcePath queryParams:(NSDictionary*)queryParams delegate:(id)delegate {
NSString* resourcePathWithQueryString = [NSString stringWithFormat:@"%@?%@", resourcePath, [queryParams URLEncodedString]];
return [self load:resourcePathWithQueryString method:RKRequestMethodGET params:nil delegate:delegate callback:callback];
return [self load:resourcePathWithQueryString method:RKRequestMethodGET params:nil delegate:delegate];
}
- (RKRequest*)post:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate callback:(SEL)callback {
return [self load:resourcePath method:RKRequestMethodPOST params:params delegate:delegate callback:callback];
- (RKRequest*)post:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate {
return [self load:resourcePath method:RKRequestMethodPOST params:params delegate:delegate];
}
- (RKRequest*)put:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate callback:(SEL)callback {
return [self load:resourcePath method:RKRequestMethodPUT params:params delegate:delegate callback:callback];
- (RKRequest*)put:(NSString*)resourcePath params:(NSObject<RKRequestSerializable>*)params delegate:(id)delegate {
return [self load:resourcePath method:RKRequestMethodPUT params:params delegate:delegate];
}
- (RKRequest*)delete:(NSString*)resourcePath delegate:(id)delegate callback:(SEL)callback {
return [self load:resourcePath method:RKRequestMethodDELETE params:nil delegate:delegate callback:callback];
- (RKRequest*)delete:(NSString*)resourcePath delegate:(id)delegate {
return [self load:resourcePath method:RKRequestMethodDELETE params:nil delegate:delegate];
}
@end

View File

@@ -18,3 +18,4 @@
*/
extern NSString* const kRKRequestSentNotification;
extern NSString* const kRKResponseReceivedNotification;
extern NSString* const kRKRequestFailedWithErrorNotification;

View File

@@ -10,3 +10,4 @@
NSString* const kRKRequestSentNotification = @"kRKRequestSentNotification";
NSString* const kRKResponseReceivedNotification = @"kRKRespongReceivedNotification";
NSString* const kRKRequestFailedWithErrorNotification = @"kRKRequestFailedWithErrorNotification";

View File

@@ -22,6 +22,7 @@ typedef enum RKRequestMethod {
} RKRequestMethod;
@class RKResponse;
@protocol RKRequestDelegate;
@interface RKRequest : NSObject {
NSURL* _URL;
@@ -29,8 +30,7 @@ typedef enum RKRequestMethod {
NSURLConnection* _connection;
NSDictionary* _additionalHTTPHeaders;
NSObject<RKRequestSerializable>* _params;
id _delegate;
SEL _callback;
NSObject<RKRequestDelegate>* _delegate;
id _userData;
NSString* _username;
NSString* _password;
@@ -42,6 +42,11 @@ typedef enum RKRequestMethod {
*/
@property(nonatomic, readonly) NSURL* URL;
/**
* The resourcePath portion of this loader's URL
*/
@property (nonatomic, readonly) NSString* resourcePath;
/**
* The HTTP verb the request is sent via
*
@@ -61,12 +66,7 @@ typedef enum RKRequestMethod {
* If the object implements the RKRequestDelegate protocol,
* it will receive request lifecycle event messages.
*/
@property(nonatomic, assign) id delegate;
/**
* The selector to invoke when the request is completed
*/
@property(nonatomic, assign) SEL callback;
@property(nonatomic, assign) NSObject<RKRequestDelegate>* delegate;
/**
* A Dictionary of additional HTTP Headers to send with the request
@@ -100,7 +100,7 @@ typedef enum RKRequestMethod {
/**
* Return a REST request that is ready for dispatching
*/
+ (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate callback:(SEL)callback;
+ (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate;
/**
* Initialize a synchronous request
@@ -110,10 +110,11 @@ typedef enum RKRequestMethod {
/**
* Initialize a REST request and prepare it for dispatching
*/
- (id)initWithURL:(NSURL*)URL delegate:(id)delegate callback:(SEL)callback;
- (id)initWithURL:(NSURL*)URL delegate:(id)delegate;
/**
* Send the request asynchronously
* Send the request asynchronously. It will be added to the queue and
* dispatched as soon as possible.
*/
- (void)send;
@@ -154,18 +155,13 @@ typedef enum RKRequestMethod {
*
* Modeled off of TTURLRequest
*/
@protocol RKRequestDelegate
@protocol RKRequestDelegate
@optional
/**
* Sent when a request has started loading
*/
- (void)requestDidStartLoad:(RKRequest*)request;
/**
* Sent when a request has finished loading
*/
- (void)requestDidFinishLoad:(RKRequest*)request;
- (void)requestDidFinishLoad:(RKRequest*)request withResponse:(RKResponse*)response;
/**
* Sent when a request has failed due to an error
@@ -173,9 +169,9 @@ typedef enum RKRequestMethod {
- (void)request:(RKRequest*)request didFailLoadWithError:(NSError*)error;
/**
* Sent when a request has been canceled
* Sent when a request has started loading
*/
- (void)requestDidCancelLoad:(RKRequest*)request;
- (void)requestDidStartLoad:(RKRequest*)request;
/**
* Sent when a request has uploaded data to the remote site

View File

@@ -7,19 +7,21 @@
//
#import "RKRequest.h"
#import "RKRequestQueue.h"
#import "RKResponse.h"
#import "NSDictionary+RKRequestSerialization.h"
#import "RKNotifications.h"
#import "RKClient.h"
#import "../Support/Support.h"
#import "RKURL.h"
@implementation RKRequest
@synthesize URL = _URL, URLRequest = _URLRequest, delegate = _delegate, callback = _callback, additionalHTTPHeaders = _additionalHTTPHeaders,
@synthesize URL = _URL, URLRequest = _URLRequest, delegate = _delegate, additionalHTTPHeaders = _additionalHTTPHeaders,
params = _params, userData = _userData, username = _username, password = _password, method = _method;
+ (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate callback:(SEL)callback {
RKRequest* request = [[RKRequest alloc] initWithURL:URL delegate:delegate callback:callback];
+ (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate {
RKRequest* request = [[RKRequest alloc] initWithURL:URL delegate:delegate];
[request autorelease];
return request;
@@ -35,10 +37,9 @@
return self;
}
- (id)initWithURL:(NSURL*)URL delegate:(id)delegate callback:(SEL)callback {
- (id)initWithURL:(NSURL*)URL delegate:(id)delegate {
if (self = [self initWithURL:URL]) {
_delegate = delegate;
_callback = callback;
}
return self;
@@ -117,6 +118,10 @@
}
- (void)send {
[[RKRequestQueue sharedQueue] sendRequest:self];
}
- (void)fireAsynchronousRequest {
if ([[RKClient sharedClient] isNetworkAvailable]) {
[self addHeadersToRequest];
NSString* body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding];
@@ -171,9 +176,6 @@
[_connection cancel];
[_connection release];
_connection = nil;
if ([_delegate respondsToSelector:@selector(requestDidCancelLoad:)]) {
[_delegate requestDidCancelLoad:self];
}
}
- (BOOL)isGET {
@@ -192,4 +194,13 @@
return _method == RKRequestMethodDELETE;
}
- (NSString*)resourcePath {
NSString* resourcePath = nil;
if ([self.URL isKindOfClass:[RKURL class]]) {
RKURL* url = (RKURL*)self.URL;
resourcePath = url.resourcePath;
}
return resourcePath;
}
@end

View File

@@ -0,0 +1,63 @@
//
// RKRequestQueue.h
// RestKit
//
// Created by Blake Watters on 12/1/10.
// Copyright 2010 Two Toasters. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RKRequest.h"
/**
* A lightweight queue implementation responsible
* for dispatching and managing RKRequest objects
*/
@interface RKRequestQueue : NSObject {
NSMutableArray* _requests;
NSInteger _totalLoading;
NSTimer* _queueTimer;
BOOL _suspended;
}
/**
* Gets the flag that determines if new load requests are allowed to reach the network.
*
* Because network requests tend to slow down performance, this property can be used to
* temporarily delay them. All requests made while suspended are queued, and when
* suspended becomes false again they are executed.
*/
@property (nonatomic) BOOL suspended;
/**
* Return the global queue
*/
+ (RKRequestQueue*)sharedQueue;
/**
* Set the global queue
*/
+ (void)setSharedQueue:(RKRequestQueue*)requestQueue;
/**
* Add an asynchronous request to the queue and send it as
* as soon as possible
*/
- (void)sendRequest:(RKRequest*)request;
/**
* Cancel a request that is in progress
*/
- (void)cancelRequest:(RKRequest*)request;
/**
* Cancel all requests with a given delegate
*/
- (void)cancelRequestsWithDelegate:(NSObject<RKRequestDelegate>*)delegate;
/**
* Cancel all active or pending requests.
*/
- (void)cancelAllRequests;
@end

View File

@@ -0,0 +1,153 @@
//
// RKRequestQueue.m
// RestKit
//
// Created by Blake Watters on 12/1/10.
// Copyright 2010 Two Toasters. All rights reserved.
//
#import "RKRequestQueue.h"
#import "RKResponse.h"
#import "RKNotifications.h"
static RKRequestQueue* gSharedQueue = nil;
static const NSTimeInterval kFlushDelay = 0.3;
static const NSTimeInterval kTimeout = 300.0;
static const NSInteger kMaxConcurrentLoads = 5;
@implementation RKRequestQueue
@synthesize suspended = _suspended;
+ (RKRequestQueue*)sharedQueue {
if (!gSharedQueue) {
gSharedQueue = [[RKRequestQueue alloc] init];
}
return gSharedQueue;
}
+ (void)setSharedQueue:(RKRequestQueue*)requestQueue {
if (gSharedQueue != requestQueue) {
[gSharedQueue release];
gSharedQueue = [requestQueue retain];
}
}
- (id)init {
if (self = [super init]) {
_requests = [[NSMutableArray alloc] init];
_suspended = NO;
_totalLoading = 0;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(responseDidLoad:)
name:kRKResponseReceivedNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(responseDidLoad:)
name:kRKRequestFailedWithErrorNotification
object:nil];
}
return self;
}
- (void)dealloc {
[_queueTimer invalidate];
[_requests release];
_requests = nil;
[super dealloc];
}
- (void)loadNextInQueueDelayed {
if (!_queueTimer) {
_queueTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushDelay
target:self
selector:@selector(loadNextInQueue)
userInfo:nil
repeats:NO];
}
}
- (void)dispatchRequest:(RKRequest*)request {
[request performSelector:@selector(fireAsynchronousRequest)];
}
- (void)loadNextInQueue {
_queueTimer = nil;
for (int i = _totalLoading;
i < kMaxConcurrentLoads && i < _requests.count;
++i) {
RKRequest* request = [_requests objectAtIndex:i];
++_totalLoading;
[self dispatchRequest:request];
}
if (_requests.count && !_suspended) {
[self loadNextInQueueDelayed];
}
}
- (void)setSuspended:(BOOL)isSuspended {
_suspended = isSuspended;
if (!_suspended) {
[self loadNextInQueue];
} else if (_queueTimer) {
[_queueTimer invalidate];
_queueTimer = nil;
}
}
- (void)sendRequest:(RKRequest*)request {
[_requests addObject:request];
NSLog(@"Request added: URL=%@", [request URL]);
[self loadNextInQueue];
}
- (void)cancelRequest:(RKRequest*)request {
if ([_requests containsObject:request]) {
[request cancel];
NSLog(@"Request cancelled and removed: URL=%@", [request URL]);
[_requests removeObject:request];
_totalLoading--;
[self loadNextInQueue];
}
}
- (void)cancelRequestsWithDelegate:(NSObject<RKRequestDelegate>*)delegate {
for (RKRequest* request in _requests) {
if (request.delegate && request.delegate == delegate) {
[request cancel];
}
}
}
- (void)cancelAllRequests {
for (RKRequest* request in [[[_requests copy] autorelease] objectEnumerator]) {
[request cancel];
}
}
/**
* Invoked via observation when a request has loaded a response. Remove
* the completed request from the queue and continue processing
*/
- (void)responseDidLoad:(NSNotification*)notification {
if (notification.object && [notification.object isKindOfClass:[RKResponse class]]) {
RKResponse* response = (RKResponse*)notification.object;
[_requests removeObject:[response request]];
_totalLoading--;
[self loadNextInQueue];
NSError* error = (NSError*)[notification.userInfo objectForKey:@"error"];
if (error) {
NSLog(@"Request failed and removed: URL=%@, error=%@", [[response request] URL], error);
} else {
NSLog(@"Request completed and removed: URL=%@", [[response request] URL]);
}
}
}
@end

View File

@@ -26,7 +26,9 @@
- (id)initWithRequest:(RKRequest*)request {
if (self = [self init]) {
_request = [request retain];
// We don't retain here as we're letting RKRequestQueue manage
// request ownership
_request = request;
}
return self;
@@ -34,9 +36,7 @@
- (id)initWithRequest:(RKRequest*)request error:(NSError*)error {
if (self = [self initWithRequest:request]) {
_failureError = [error retain];
[[_request delegate] performSelector:[_request callback] withObject:self];
_failureError = [error retain];
if ([[_request delegate] respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[[_request delegate] request:_request didFailLoadWithError:error];
}
@@ -60,13 +60,12 @@
- (void)dealloc {
[_httpURLResponse release];
[_body release];
[_request release];
[_failureError release];
[super dealloc];
}
// Handle basic auth
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:[NSString stringWithFormat:@"%@", _request.username]
@@ -94,25 +93,26 @@
_httpURLResponse = [response retain];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDate* receivedAt = [NSDate date]; // TODO - Carry around this timestamp on the response or request?
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_request HTTPMethod], @"HTTPMethod", [_request URL], @"URL", receivedAt, @"receivedAt", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:kRKResponseReceivedNotification object:self userInfo:userInfo];
[[_request delegate] performSelector:[_request callback] withObject:self];
if ([[_request delegate] respondsToSelector:@selector(requestDidFinishLoad:)]) {
[[_request delegate] requestDidFinishLoad:_request];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ([[_request delegate] respondsToSelector:@selector(requestDidFinishLoad:withResponse:)]) {
[[_request delegate] requestDidFinishLoad:_request withResponse:self];
}
NSDate* receivedAt = [NSDate date];
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_request HTTPMethod], @"HTTPMethod", [_request URL], @"URL", receivedAt, @"receivedAt", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:kRKResponseReceivedNotification object:self userInfo:userInfo];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
_failureError = [error retain];
[[_request delegate] performSelector:[_request callback] withObject:self];
if ([[_request delegate] respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[[_request delegate] request:_request didFailLoadWithError:error];
}
NSDate* receivedAt = [NSDate date];
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_request HTTPMethod], @"HTTPMethod",
[_request URL], @"URL", receivedAt, @"receivedAt", error, @"error", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:kRKRequestFailedWithErrorNotification object:_request userInfo:userInfo];
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
@@ -121,7 +121,6 @@
}
}
- (NSString*)localizedStatusCodeString {
return [NSHTTPURLResponse localizedStringForStatusCode:[self statusCode]];
}

View File

@@ -40,16 +40,15 @@
/**
* Wraps a request/response cycle and loads a remote object representation into local domain objects
*/
@interface RKObjectLoader : NSObject <RKRequestDelegate> {
@interface RKObjectLoader : RKRequest <RKRequestDelegate> {
RKObjectMapper* _mapper;
NSObject<RKObjectLoaderDelegate>* _delegate;
RKRequest* _request;
NSObject<RKObjectLoaderDelegate>* _objectLoaderDelegate;
RKResponse* _response;
NSObject<RKObjectMappable>* _source;
NSObject<RKObjectMappable>* _targetObject;
Class<RKObjectMappable> _objectClass;
NSString* _keyPath;
RKManagedObjectStore* _managedObjectStore;
NSManagedObjectID* _sourceObjectID;
NSManagedObjectID* _targetObjectID;
}
/**
@@ -63,12 +62,7 @@
* If this object implements life-cycle methods from the RKRequestDelegate protocol,
* events from the request will be forwarded back.
*/
@property (nonatomic, assign) NSObject<RKObjectLoaderDelegate>* delegate;
/**
* The underlying request object for this loader
*/
@property (nonatomic, retain) RKRequest* request;
@property (nonatomic, assign) NSObject<RKObjectLoaderDelegate>* objectLoaderDelegate;
/**
* The underlying response object for this loader
@@ -83,30 +77,9 @@
/**
* The mappable object that generated this loader. This is used to map object
* updates back to the source object that sent the request
* updates back to the object that sent the request
*/
// TODO: This should have a better name... targetObject?
@property (nonatomic, retain) NSObject<RKObjectMappable>* source;
/**
* The URL this loader sent the request to
*/
@property (nonatomic, readonly) NSURL* URL;
/**
* The resourcePath portion of this loader's URL
*/
@property (nonatomic, readonly) NSString* resourcePath;
/**
* The HTTP method used to send the request
*/
@property (nonatomic, assign) RKRequestMethod method;
/**
* Parameters sent with the request
*/
@property (nonatomic, retain) NSObject<RKRequestSerializable>* params;
@property (nonatomic, retain) NSObject<RKObjectMappable>* targetObject;
/*
* The keyPath property is an optional property to tell the mapper to map a subset of the response
@@ -124,21 +97,11 @@
/**
* Return an auto-released loader with with an object mapper, a request, and a delegate
*/
+ (id)loaderWithMapper:(RKObjectMapper*)mapper request:(RKRequest*)request delegate:(NSObject<RKObjectLoaderDelegate>*)delegate;
+ (id)loaderWithResourcePath:(NSString*)resourcePath mapper:(RKObjectMapper*)mapper delegate:(NSObject<RKObjectLoaderDelegate>*)delegate;
/**
* Initialize a new object loader with an object mapper, a request, and a delegate
*/
- (id)initWithMapper:(RKObjectMapper*)mapper request:(RKRequest*)request delegate:(NSObject<RKObjectLoaderDelegate>*)delegate;
/**
* Asynchronously send the object loader request
*/
- (void)send;
/**
* Synchronously send the object loader request and process the response
*/
- (void)sendSynchronously;
- (id)initWithResourcePath:(NSString*)resourcePath mapper:(RKObjectMapper*)mapper delegate:(NSObject<RKObjectLoaderDelegate>*)delegate;
@end

View File

@@ -20,122 +20,68 @@
@implementation RKObjectLoader
@synthesize mapper = _mapper, delegate = _delegate, request = _request, response = _response,
objectClass = _objectClass, source = _source, keyPath = _keyPath, managedObjectStore = _managedObjectStore;
@synthesize mapper = _mapper, objectLoaderDelegate = _objectLoaderDelegate, response = _response,
objectClass = _objectClass, targetObject = _targetObject, keyPath = _keyPath, managedObjectStore = _managedObjectStore;
+ (id)loaderWithMapper:(RKObjectMapper*)mapper request:(RKRequest*)request delegate:(NSObject<RKObjectLoaderDelegate>*)delegate {
return [[[self alloc] initWithMapper:mapper request:request delegate:delegate] autorelease];
+ (id)loaderWithResourcePath:(NSString*)resourcePath mapper:(RKObjectMapper*)mapper delegate:(NSObject<RKObjectLoaderDelegate>*)delegate {
return [[[self alloc] initWithResourcePath:resourcePath mapper:mapper delegate:delegate] autorelease];
}
- (id)initWithMapper:(RKObjectMapper*)mapper request:(RKRequest*)request delegate:(NSObject<RKObjectLoaderDelegate>*)delegate {
if (self = [self init]) {
- (id)initWithResourcePath:(NSString*)resourcePath mapper:(RKObjectMapper*)mapper delegate:(NSObject<RKObjectLoaderDelegate>*)delegate {
if (self = [self initWithURL:[[RKClient sharedClient] URLForResourcePath:resourcePath] delegate:self]) {
_mapper = [mapper retain];
self.request = request;
self.delegate = delegate;
self.objectLoaderDelegate = delegate;
self.managedObjectStore = nil;
_sourceObjectID = nil;
_targetObjectID = nil;
[[RKClient sharedClient] setupRequest:self];
}
return self;
}
- (void)dealloc {
_request.delegate = nil;
self.delegate = nil;
[_request cancel];
self.objectLoaderDelegate = nil;
[self cancel];
[_mapper release];
[_request release];
[_response release];
[_keyPath release];
self.managedObjectStore = nil;
[_sourceObjectID release];
_sourceObjectID = nil;
[_targetObjectID release];
_targetObjectID = nil;
[super dealloc];
}
- (void)setRequest:(RKRequest *)request {
[request retain];
[_request release];
_request = request;
- (void)setTargetObject:(NSObject<RKObjectMappable>*)targetObject {
[_targetObject release];
_targetObject = nil;
_targetObject = [targetObject retain];
_request.delegate = self;
_request.callback = @selector(loadObjectsFromResponse:);
}
#pragma mark RKRequest Proxy Methods
- (NSURL*)URL {
return self.request.URL;
}
- (NSString*)resourcePath {
NSString* resourcePath = nil;
if ([self.request.URL isKindOfClass:[RKURL class]]) {
RKURL* url = (RKURL*)self.request.URL;
resourcePath = url.resourcePath;
}
return resourcePath;
}
- (RKRequestMethod)method {
return self.request.method;
}
- (void)setMethod:(RKRequestMethod)method {
self.request.method = method;
}
- (NSObject<RKRequestSerializable>*)params {
return self.request.params;
}
- (void)setParams:(NSObject<RKRequestSerializable>*)params {
self.request.params = params;
}
- (void)setSource:(NSObject<RKObjectMappable>*)source {
[_source release];
_source = nil;
_source = [source retain];
[_targetObjectID release];
_targetObjectID = nil;
[_sourceObjectID release];
_sourceObjectID = nil;
if ([source isKindOfClass:[NSManagedObject class]]) {
_sourceObjectID = [[(NSManagedObject*)source objectID] retain];
if ([targetObject isKindOfClass:[NSManagedObject class]]) {
_targetObjectID = [[(NSManagedObject*)targetObject objectID] retain];
}
}
- (void)send {
[self retain];
[self.request send];
}
- (void)sendSynchronously {
[self retain];
RKResponse* response = [self.request sendSynchronously];
[self loadObjectsFromResponse:response];
}
#pragma mark Response Processing
- (BOOL)encounteredErrorWhileProcessingRequest:(RKResponse*)response {
if ([response isFailure]) {
[_delegate objectLoader:self didFailWithError:response.failureError];
[self release];
[_objectLoaderDelegate objectLoader:self didFailWithError:response.failureError];
return YES;
} else if ([response isError]) {
if ([response isJSON]) {
[_delegate objectLoader:self didFailWithError:[_mapper parseErrorFromString:[response bodyAsString]]];
[_objectLoaderDelegate objectLoader:self didFailWithError:[_mapper parseErrorFromString:[response bodyAsString]]];
} else {
if ([_delegate respondsToSelector:@selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[_delegate objectLoaderDidLoadUnexpectedResponse:self];
if ([_objectLoaderDelegate respondsToSelector:@selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[_objectLoaderDelegate objectLoaderDidLoadUnexpectedResponse:self];
}
}
[self release];
return YES;
}
return NO;
}
@@ -155,8 +101,7 @@
}
}
[_delegate objectLoader:self didLoadObjects:[NSArray arrayWithArray:objects]];
[self release];
[_objectLoaderDelegate objectLoader:self didLoadObjects:[NSArray arrayWithArray:objects]];
}
- (void)informDelegateOfObjectLoadErrorWithInfoDictionary:(NSDictionary*)dictionary {
@@ -170,8 +115,7 @@
nil];
NSError *rkError = [NSError errorWithDomain:RKRestKitErrorDomain code:RKObjectLoaderRemoteSystemError userInfo:userInfo];
[_delegate objectLoader:self didFailWithError:rkError];
[self release];
[_objectLoaderDelegate objectLoader:self didFailWithError:rkError];
}
@@ -185,14 +129,14 @@
* individual object instances via getObject & friends.
*/
NSArray* results = nil;
if (self.source) {
if (_sourceObjectID) {
NSManagedObject* backgroundThreadModel = [self.managedObjectStore objectWithID:_sourceObjectID];
if (self.targetObject) {
if (_targetObjectID) {
NSManagedObject* backgroundThreadModel = [self.managedObjectStore objectWithID:_targetObjectID];
[_mapper mapObject:backgroundThreadModel fromString:[response bodyAsString]];
results = [NSArray arrayWithObject:backgroundThreadModel];
} else {
[_mapper mapObject:self.source fromString:[response bodyAsString]];
results = [NSArray arrayWithObject:self.source];
[_mapper mapObject:self.targetObject fromString:[response bodyAsString]];
results = [NSArray arrayWithObject:self.targetObject];
}
} else {
id result = [_mapper mapFromString:[response bodyAsString] toClass:self.objectClass keyPath:_keyPath];
@@ -246,7 +190,18 @@
[pool release];
}
- (void)loadObjectsFromResponse:(RKResponse*)response {
///////////////////////////////////////////////////////////////////////////////////////////////////
// RKRequestDelegate
//
// If our delegate responds to the messages, forward them back...
- (void)requestDidStartLoad:(RKRequest*)request {
if ([_objectLoaderDelegate respondsToSelector:@selector(requestDidStartLoad:)]) {
[_objectLoaderDelegate requestDidStartLoad:request];
}
}
- (void)requestDidFinishLoad:(RKRequest*)request withResponse:(RKResponse*)response {
_response = [response retain];
if (NO == [self encounteredErrorWhileProcessingRequest:response]) {
@@ -255,47 +210,26 @@
[self performSelectorInBackground:@selector(processLoadModelsInBackground:) withObject:response];
} else {
NSLog(@"Encountered unexpected response code: %d (MIME Type: %@)", response.statusCode, response.MIMEType);
if ([_delegate respondsToSelector:@selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[_delegate objectLoaderDidLoadUnexpectedResponse:self];
[self release];
if ([_objectLoaderDelegate respondsToSelector:@selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[_objectLoaderDelegate objectLoaderDidLoadUnexpectedResponse:self];
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// RKRequestDelegate
//
// If our delegate responds to the messages, forward them back...
- (void)requestDidStartLoad:(RKRequest*)request {
if ([_delegate respondsToSelector:@selector(requestDidStartLoad:)]) {
[_delegate requestDidStartLoad:request];
}
}
- (void)requestDidFinishLoad:(RKRequest*)request {
if ([_delegate respondsToSelector:@selector(requestDidFinishLoad:)]) {
[(NSObject<RKRequestDelegate>*)_delegate requestDidFinishLoad:request];
if ([_objectLoaderDelegate respondsToSelector:@selector(requestDidFinishLoad:)]) {
[(NSObject<RKRequestDelegate>*)_objectLoaderDelegate requestDidFinishLoad:request withResponse:response];
}
}
- (void)request:(RKRequest*)request didFailLoadWithError:(NSError*)error {
if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[(NSObject<RKRequestDelegate>*)_delegate request:request didFailLoadWithError:error];
}
}
- (void)requestDidCancelLoad:(RKRequest*)request {
[self release];
if ([_delegate respondsToSelector:@selector(requestDidCancelLoad:)]) {
[(NSObject<RKRequestDelegate>*)_delegate requestDidCancelLoad:request];
if ([_objectLoaderDelegate respondsToSelector:@selector(request:didFailLoadWithError:)]) {
[(NSObject<RKRequestDelegate>*)_objectLoaderDelegate request:request didFailLoadWithError:error];
}
}
- (void)request:(RKRequest*)request didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
if ([_delegate respondsToSelector:@selector(request:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)]) {
[(NSObject<RKRequestDelegate>*)_delegate request:request didSendBodyData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
if ([_objectLoaderDelegate respondsToSelector:@selector(request:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)]) {
[(NSObject<RKRequestDelegate>*)_objectLoaderDelegate request:request didSendBodyData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
}

View File

@@ -138,9 +138,7 @@ static RKObjectManager* sharedManager = nil;
}
- (RKObjectLoader*)objectLoaderWithResourcePath:(NSString*)resourcePath delegate:(NSObject<RKObjectLoaderDelegate>*)delegate {
// Grab request through client to get HTTP AUTH & Headers
RKRequest* request = [self.client requestWithResourcePath:resourcePath delegate:nil callback:nil];
RKObjectLoader* loader = [RKObjectLoader loaderWithMapper:self.mapper request:request delegate:delegate];
RKObjectLoader* loader = [RKObjectLoader loaderWithResourcePath:resourcePath mapper:self.mapper delegate:delegate];
loader.managedObjectStore = self.objectStore;
return loader;
@@ -205,7 +203,7 @@ static RKObjectManager* sharedManager = nil;
loader.method = method;
loader.params = params;
loader.source = object;
loader.targetObject = object;
loader.objectClass = [object class];
loader.managedObjectStore = self.objectStore;

View File

@@ -13,7 +13,7 @@
* Generic class for loading a remote model using a RestKit request and supplying the model to a
* TTListDataSource subclass
*/
@interface RKRequestTTModel : TTModel <RKObjectLoaderDelegate, RKRequestDelegate> {
@interface RKRequestTTModel : TTModel <RKObjectLoaderDelegate> {
NSArray *_objects;
BOOL _loaded;
BOOL _cacheLoaded;

View File

@@ -8,6 +8,7 @@
#import "RKRequestTTModel.h"
#import "RKManagedObjectStore.h"
#import "../Network/Network.h"
static NSTimeInterval defaultRefreshRate = NSTimeIntervalSince1970;
static NSString* const kDefaultLoadedTimeKey = @"RKRequestTTModelDefaultLoadedTimeKey";
@@ -104,8 +105,8 @@ static NSString* const kDefaultLoadedTimeKey = @"RKRequestTTModelDefaultLoadedTi
}
- (void)dealloc {
[_objectLoader setDelegate:nil];
[self cancel];
[_objectLoader setObjectLoaderDelegate:nil];
[[RKRequestQueue sharedQueue] cancelRequest:_objectLoader];
[_objectLoader release];
_objectLoader = nil;
[_objects release];
@@ -138,9 +139,10 @@ static NSString* const kDefaultLoadedTimeKey = @"RKRequestTTModelDefaultLoadedTi
}
- (void)cancel {
if (_objectLoader && _objectLoader.request) {
[_objectLoader.request cancel];
}
[[RKRequestQueue sharedQueue] cancelRequest:_objectLoader];
[_objectLoader release];
_objectLoader = nil;
[self didCancelLoad];
}
- (void)invalidate:(BOOL)erase {
@@ -190,22 +192,6 @@ static NSString* const kDefaultLoadedTimeKey = @"RKRequestTTModelDefaultLoadedTi
}
#pragma mark RKRequestDelegate
- (void)requestDidFinishLoad:(RKRequest*)request {
[self saveLoadedTime];
[self didFinishLoad];
}
- (void)request:(RKRequest*)request didFailLoadWithError:(NSError*)error {
[self didFailLoadWithError:error];
}
- (void)requestDidCancelLoad:(RKRequest*)request {
[self didCancelLoad];
}
#pragma mark RKRequestTTModel (Private)
- (void)clearLoadedTime {
@@ -257,6 +243,7 @@ static NSString* const kDefaultLoadedTimeKey = @"RKRequestTTModelDefaultLoadedTi
_objects = models;
_loaded = YES;
[self saveLoadedTime];
[self didFinishLoad];
}

View File

@@ -34,6 +34,8 @@
2520776E113587BE00382018 /* NSDictionary+RKRequestSerializationSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 2520776D113587BE00382018 /* NSDictionary+RKRequestSerializationSpec.m */; };
2523363E11E7A1F00048F9B4 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F6C3A9510FE7524008F47C5 /* UIKit.framework */; };
2524CB5D1278930200D1314C /* RKParamsAttachmentSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 2524CB5C1278930200D1314C /* RKParamsAttachmentSpec.m */; };
2538C05C12A6C44A0006903C /* RKRequestQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 2538C05A12A6C44A0006903C /* RKRequestQueue.h */; settings = {ATTRIBUTES = (Public, ); }; };
2538C05D12A6C44A0006903C /* RKRequestQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 2538C05B12A6C44A0006903C /* RKRequestQueue.m */; };
253A08AF12551EA500976E89 /* Network.h in Headers */ = {isa = PBXBuildFile; fileRef = 253A08AE12551EA500976E89 /* Network.h */; settings = {ATTRIBUTES = (Public, ); }; };
253A08CC125522CE00976E89 /* NSDictionary+RKRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 253A086612551D8D00976E89 /* NSDictionary+RKRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; };
253A08CD125522D000976E89 /* NSDictionary+RKRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 253A086712551D8D00976E89 /* NSDictionary+RKRequestSerialization.m */; };
@@ -407,6 +409,8 @@
2520776D113587BE00382018 /* NSDictionary+RKRequestSerializationSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSDictionary+RKRequestSerializationSpec.m"; sourceTree = "<group>"; };
2523360511E79F090048F9B4 /* libRestKitThree20.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRestKitThree20.a; sourceTree = BUILT_PRODUCTS_DIR; };
2524CB5C1278930200D1314C /* RKParamsAttachmentSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RKParamsAttachmentSpec.m; sourceTree = "<group>"; };
2538C05A12A6C44A0006903C /* RKRequestQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RKRequestQueue.h; sourceTree = "<group>"; };
2538C05B12A6C44A0006903C /* RKRequestQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RKRequestQueue.m; sourceTree = "<group>"; };
253A07FC1255161B00976E89 /* libRestKitNetwork.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRestKitNetwork.a; sourceTree = BUILT_PRODUCTS_DIR; };
253A08031255162C00976E89 /* libRestKitObjectMapping.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRestKitObjectMapping.a; sourceTree = BUILT_PRODUCTS_DIR; };
253A080C12551D3000976E89 /* libRestKitSupport.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRestKitSupport.a; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -838,6 +842,8 @@
253A087B12551D8D00976E89 /* RKResponse.m */,
73FE56C4126CB91600E0F30B /* RKURL.h */,
73FE56C5126CB91600E0F30B /* RKURL.m */,
2538C05A12A6C44A0006903C /* RKRequestQueue.h */,
2538C05B12A6C44A0006903C /* RKRequestQueue.m */,
);
path = Network;
sourceTree = "<group>";
@@ -1200,6 +1206,7 @@
253A08E0125522E300976E89 /* RKResponse.h in Headers */,
73FE56C7126CB91600E0F30B /* RKURL.h in Headers */,
73C89EF212A5BB9A000FE600 /* RKReachabilityObserver.h in Headers */,
2538C05C12A6C44A0006903C /* RKRequestQueue.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1665,6 +1672,7 @@
253A08E1125522E400976E89 /* RKResponse.m in Sources */,
73FE56C8126CB91600E0F30B /* RKURL.m in Sources */,
73C89EF312A5BB9A000FE600 /* RKReachabilityObserver.m in Sources */,
2538C05D12A6C44A0006903C /* RKRequestQueue.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1826,7 +1834,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
SDKROOT = iphoneos4.1;
SDKROOT = iphoneos;
USER_HEADER_SEARCH_PATHS = ../ElementParser/Classes;
};
name = Debug;