Browse files

Merge branch 'development'

2 parents 6735369 + 290c3b4 commit b4a240169a35fd2a58a1999f815fe5015241acce @valeriomazzeo valeriomazzeo committed Jul 9, 2016
Showing with 7,572 additions and 1,943 deletions.
  1. +1 −1 .ruby-version
  2. +11 −4 .travis.yml
  3. +1 −1 Code/CocoaLumberjack/RKLumberjackLogger.h
  4. +2 −2 Code/CocoaLumberjack/RKLumberjackLogger.m
  5. +11 −11 Code/CoreData.h
  6. +4 −4 Code/CoreData/NSManagedObject+RKAdditions.m
  7. +2 −2 Code/CoreData/NSManagedObjectContext+RKAdditions.m
  8. +1 −1 Code/CoreData/RKConnectionDescription.m
  9. +0 −26 Code/CoreData/RKCoreData.h
  10. +20 −38 Code/CoreData/RKEntityByAttributeCache.m
  11. +18 −0 Code/CoreData/RKEntityCache.h
  12. +73 −7 Code/CoreData/RKEntityCache.m
  13. +3 −3 Code/CoreData/RKEntityMapping.h
  14. +7 −7 Code/CoreData/RKEntityMapping.m
  15. +1 −1 Code/CoreData/RKFetchRequestManagedObjectCache.h
  16. +30 −12 Code/CoreData/RKFetchRequestManagedObjectCache.m
  17. +1 −1 Code/CoreData/RKInMemoryManagedObjectCache.h
  18. +8 −5 Code/CoreData/RKInMemoryManagedObjectCache.m
  19. +8 −8 Code/CoreData/RKManagedObjectImporter.m
  20. +1 −1 Code/CoreData/RKManagedObjectMappingOperationDataSource.h
  21. +14 −14 Code/CoreData/RKManagedObjectMappingOperationDataSource.m
  22. +2 −2 Code/CoreData/RKManagedObjectStore.h
  23. +8 −10 Code/CoreData/RKManagedObjectStore.m
  24. +1 −1 Code/CoreData/RKPropertyInspector+CoreData.h
  25. +4 −4 Code/CoreData/RKPropertyInspector+CoreData.m
  26. +8 −8 Code/CoreData/RKRelationshipConnectionOperation.m
  27. +12 −12 Code/Network.h
  28. +651 −0 Code/Network/AFNetworking/AFRKHTTPClient.h
  29. +1,403 −0 Code/Network/AFNetworking/AFRKHTTPClient.m
  30. +133 −0 Code/Network/AFNetworking/AFRKHTTPRequestOperation.h
  31. +327 −0 Code/Network/AFNetworking/AFRKHTTPRequestOperation.m
  32. +113 −0 Code/Network/AFNetworking/AFRKImageRequestOperation.h
  33. +321 −0 Code/Network/AFNetworking/AFRKImageRequestOperation.m
  34. +71 −0 Code/Network/AFNetworking/AFRKJSONRequestOperation.h
  35. +150 −0 Code/Network/AFNetworking/AFRKJSONRequestOperation.m
  36. +75 −0 Code/Network/AFNetworking/AFRKNetworkActivityIndicatorManager.h
  37. +157 −0 Code/Network/AFNetworking/AFRKNetworkActivityIndicatorManager.m
  38. +54 −0 Code/Network/AFNetworking/AFRKNetworking.h
  39. +68 −0 Code/Network/AFNetworking/AFRKPropertyListRequestOperation.h
  40. +143 −0 Code/Network/AFNetworking/AFRKPropertyListRequestOperation.m
  41. +370 −0 Code/Network/AFNetworking/AFRKURLConnectionOperation.h
  42. +862 −0 Code/Network/AFNetworking/AFRKURLConnectionOperation.m
  43. +89 −0 Code/Network/AFNetworking/AFRKXMLRequestOperation.h
  44. +167 −0 Code/Network/AFNetworking/AFRKXMLRequestOperation.m
  45. +78 −0 Code/Network/AFNetworking/UIImageView+AFRKNetworking.h
  46. +191 −0 Code/Network/AFNetworking/UIImageView+AFRKNetworking.m
  47. +4 −4 Code/Network/RKHTTPRequestOperation.h
  48. +9 −16 Code/Network/RKHTTPRequestOperation.m
  49. 0 Code/{ObjectMapping → Network}/RKHTTPUtilities.h
  50. +1 −1 Code/{ObjectMapping → Network}/RKHTTPUtilities.m
  51. +3 −3 Code/Network/RKManagedObjectRequestOperation.h
  52. +27 −17 Code/Network/RKManagedObjectRequestOperation.m
  53. +10 −12 Code/Network/RKObjectManager.h
  54. +41 −41 Code/Network/RKObjectManager.m
  55. +1 −1 Code/Network/RKObjectParameterization.h
  56. +11 −11 Code/Network/RKObjectParameterization.m
  57. +4 −4 Code/Network/RKObjectRequestOperation.h
  58. +44 −39 Code/Network/RKObjectRequestOperation.m
  59. +5 −5 Code/Network/RKPaginator.h
  60. +9 −11 Code/Network/RKPaginator.m
  61. +4 −4 Code/Network/RKPathMatcher.m
  62. +1 −1 Code/Network/RKRequestDescriptor.h
  63. +3 −3 Code/Network/RKRequestDescriptor.m
  64. +1 −1 Code/Network/RKResponseDescriptor.h
  65. +4 −4 Code/Network/RKResponseDescriptor.m
  66. +5 −5 Code/Network/RKResponseMapperOperation.h
  67. +12 −14 Code/Network/RKResponseMapperOperation.m
  68. +1 −1 Code/Network/RKRoute.h
  69. +1 −1 Code/Network/RKRoute.m
  70. +1 −1 Code/Network/RKRouteSet.h
  71. +2 −2 Code/Network/RKRouteSet.m
  72. +1 −1 Code/Network/RKRouter.h
  73. +4 −4 Code/Network/RKRouter.m
  74. +7 −7 Code/ObjectMapping.h
  75. +1 −1 Code/ObjectMapping/RKAttributeMapping.h
  76. +1 −1 Code/ObjectMapping/RKAttributeMapping.m
  77. +2 −2 Code/ObjectMapping/RKDynamicMapping.h
  78. +3 −3 Code/ObjectMapping/RKDynamicMapping.m
  79. +1 −1 Code/ObjectMapping/RKErrorMessage.m
  80. +5 −5 Code/ObjectMapping/RKMapperOperation.h
  81. +8 −8 Code/ObjectMapping/RKMapperOperation.m
  82. +1 −1 Code/ObjectMapping/RKMapping.m
  83. +1 −1 Code/ObjectMapping/RKMappingErrors.h
  84. +7 −3 Code/ObjectMapping/RKMappingOperation.h
  85. +23 −19 Code/ObjectMapping/RKMappingOperation.m
  86. +1 −1 Code/ObjectMapping/RKMappingResult.m
  87. +3 −3 Code/ObjectMapping/RKObjectMapping.h
  88. +17 −8 Code/ObjectMapping/RKObjectMapping.m
  89. +1 −1 Code/ObjectMapping/RKObjectMappingMatcher.h
  90. +2 −2 Code/ObjectMapping/RKObjectMappingMatcher.m
  91. +1 −1 Code/ObjectMapping/RKObjectMappingOperationDataSource.h
  92. +3 −3 Code/ObjectMapping/RKObjectMappingOperationDataSource.m
  93. +1 −1 Code/ObjectMapping/RKObjectUtilities.m
  94. +3 −3 Code/ObjectMapping/RKPropertyInspector.m
  95. +2 −2 Code/ObjectMapping/RKPropertyMapping.m
  96. +1 −1 Code/ObjectMapping/RKRelationshipMapping.h
  97. +2 −2 Code/ObjectMapping/RKRelationshipMapping.m
  98. +5 −5 Code/RestKit.h
  99. +4 −4 Code/Search.h
  100. +2 −2 Code/Search/RKManagedObjectStore+RKSearchAdditions.h
  101. +2 −2 Code/Search/RKManagedObjectStore+RKSearchAdditions.m
  102. +7 −7 Code/Search/RKSearchIndexer.m
  103. +2 −2 Code/Search/RKSearchPredicate.m
  104. +2 −2 Code/Search/RKSearchWord.m
  105. +1 −1 Code/Search/RKSearchWordEntity.m
  106. +10 −10 Code/Support.h
  107. +1 −1 Code/Support/RKDictionaryUtilities.m
  108. +2 −2 Code/Support/RKDotNetDateFormatter.m
  109. +1 −1 Code/Support/RKErrors.m
  110. +7 −2 Code/Support/RKLog.h
  111. +5 −5 Code/Support/RKLog.m
  112. +2 −2 Code/Support/RKMIMETypeSerialization.h
  113. +6 −6 Code/Support/RKMIMETypeSerialization.m
  114. +2 −0 Code/Support/RKMIMETypes.h
  115. +1 −1 Code/Support/RKMIMETypes.m
  116. +1 −1 Code/Support/RKNSJSONSerialization.h
  117. +1 −1 Code/Support/RKNSJSONSerialization.m
  118. +2 −2 Code/Support/RKOperationStateMachine.m
  119. +7 −25 Code/Support/RKPathUtilities.m
  120. +2 −0 Code/Support/RKSerialization.h
  121. +1 −1 Code/Support/RKStringTokenizer.m
  122. +1 −1 Code/Support/RKURLEncodedSerialization.h
  123. +1 −1 Code/Support/RKURLEncodedSerialization.m
  124. +0 −22 Code/Support/RestKit-Prefix.pch
  125. +0 −1 Code/Support/lcl_RK.h
  126. +389 −0 Code/Support/lcl_RK.h
  127. +0 −1 Code/Support/lcl_RK.m
  128. +175 −0 Code/Support/lcl_RK.m
  129. +7 −7 Code/Testing.h
  130. +1 −1 Code/Testing/RKBenchmark.m
  131. +1 −1 Code/Testing/RKConnectionTestExpectation.h
  132. +4 −3 Code/Testing/RKConnectionTestExpectation.m
  133. +28 −5 Code/Testing/RKMappingTest.h
  134. +27 −17 Code/Testing/RKMappingTest.m
  135. +2 −0 Code/Testing/RKPropertyMappingTestExpectation.h
  136. +2 −2 Code/Testing/RKPropertyMappingTestExpectation.m
  137. +2 −0 Code/Testing/RKTestConstants.m
  138. +2 −3 Code/Testing/RKTestFactory.h
  139. +12 −18 Code/Testing/RKTestFactory.m
  140. +4 −4 Code/Testing/RKTestFixture.m
  141. +2 −4 Code/Testing/RKTestHelpers.h
  142. +10 −12 Code/Testing/RKTestHelpers.m
  143. +2 −2 Code/Testing/RKTestNotificationObserver.m
  144. +8 −4 Examples/RKMacOSX/Podfile
  145. +23 −25 Examples/RKMacOSX/RKMacOSX.xcodeproj/project.pbxproj
  146. +7 −5 Examples/RKSearchExample/Podfile
  147. +23 −25 Examples/RKSearchExample/RKSearchExample.xcodeproj/project.pbxproj
  148. +1 −1 Examples/RKSearchExample/RKSearchExample/RKSAppDelegate.h
  149. +2 −2 Examples/RKTwitter/Classes/RKTwitterAppDelegate.m
  150. +1 −1 Examples/RKTwitter/Classes/RKTwitterViewController.h
  151. +1 −1 Examples/RKTwitter/Classes/RKTwitterViewController.m
  152. +6 −4 Examples/RKTwitter/Podfile
  153. +23 −25 Examples/RKTwitter/RKTwitter.xcodeproj/project.pbxproj
  154. +1 −1 Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m
  155. +9 −6 Examples/RKTwitterCoreData/Podfile
  156. +121 −16 Examples/RKTwitterCoreData/RKTwitterCoreData.xcodeproj/project.pbxproj
  157. +1 −4 Gemfile
  158. +41 −54 Gemfile.lock
  159. +21 −22 Podfile
  160. +24 −39 Podfile.lock
  161. +1 −1 README.md
  162. +17 −10 Rakefile
  163. +6 −49 RestKit.podspec
  164. +262 −217 RestKit.xcodeproj/project.pbxproj
  165. +0 −18 Tests/Logic/CoreData/RKEntityByAttributeCacheTest.m
  166. +22 −0 Tests/Logic/CoreData/RKEntityCacheTest.m
  167. +2 −2 Tests/Logic/CoreData/RKEntityMappingTest.m
  168. +23 −0 Tests/Logic/CoreData/RKFetchRequestMappingCacheTest.m
  169. +2 −4 Tests/Logic/CoreData/RKInMemoryManagedObjectCacheTest.m
  170. +1 −0 Tests/Logic/CoreData/RKManagedObjectStoreTest.m
  171. +113 −0 Tests/Logic/CoreData/RKRefetchingMappingResultTests.m
  172. +2 −0 Tests/Logic/Network/RKManagedObjectRequestOperationTest.m
  173. +29 −0 Tests/Logic/Network/RKObjectRequestOperationTest.m
  174. +9 −9 Tests/Logic/ObjectMapping/RKObjectManagerTest.m
  175. +21 −2 Tests/Logic/ObjectMapping/RKObjectMappingNextGenTest.m
  176. +12 −0 Tests/Logic/ObjectMapping/RKObjectMappingTest.m
  177. +1 −0 Tests/Logic/ObjectMapping/RKObjectParameterizationTest.m
  178. +1 −1 Tests/Logic/Search/RKSearchIndexerTest.m
  179. +1 −1 Tests/Logic/Support/RKHTTPUtilitiesTest.m
  180. BIN Tests/Models/Data Model.xcdatamodel/elements
  181. BIN Tests/Models/Data Model.xcdatamodel/layout
  182. +2 −0 Tests/Models/RKHuman.h
  183. +1 −0 Tests/Models/RKHuman.m
  184. +1 −1 Tests/README.md
  185. +1 −1 VERSION
  186. +0 −121 Vendor/LibComponentLogging/Core/README.md
  187. +0 −389 Vendor/LibComponentLogging/Core/lcl_RK.h
  188. +0 −175 Vendor/LibComponentLogging/Core/lcl_RK.m
  189. +0 −44 Vendor/LibComponentLogging/NSLog/README.md
View
2 .ruby-version
@@ -1 +1 @@
-2.2.2
+2.2.4
View
15 .travis.yml
@@ -1,10 +1,17 @@
+osx_image: xcode7.3
language: objective-c
-rvm: 2.2.2
+rvm: 2.2.4
+cache:
+ - bundler
+ - cocoapods
+before_install:
+ - gem install bundler
install:
- - bundle install
- - bundle exec pod install
+ - bundle install
+ - travis_wait 30 bundle exec pod repo update --silent
+ - travis_wait 30 bundle exec pod install
script:
- - bundle exec rake ci
+ - travis_wait 50 bundle exec rake ci
branches:
only:
- master
View
2 Code/CocoaLumberjack/RKLumberjackLogger.h
@@ -9,7 +9,7 @@
#import <Foundation/Foundation.h>
#if __has_include(<CocoaLumberjack/CocoaLumberjack.h>)
-#import <RestKit/Support/RKLog.h>
+#import "RKLog.h"
@interface RKLumberjackLogger : NSObject <RKLogging>
@end
View
4 Code/CocoaLumberjack/RKLumberjackLogger.m
@@ -7,8 +7,8 @@
//
#if __has_include(<CocoaLumberjack/CocoaLumberjack.h>)
+#import "RKLumberjackLogger.h"
#import <CocoaLumberjack/CocoaLumberjack.h>
-#import <RestKit/CocoaLumberjack/RKLumberjackLogger.h>
@implementation RKLumberjackLogger
@@ -86,7 +86,7 @@ + (void)logWithComponent:(_RKlcl_component_t)component
/* Create a DDRegisteredDynamicLogging class for each RestKit component */
-#import <RestKit/Support/lcl_config_components_RK.h>
+#import "lcl_config_components_RK.h"
#undef _RKlcl_component
#define _RKlcl_component(_identifier, _header, _name) \
View
22 Code/CoreData.h
@@ -19,15 +19,15 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/CoreData/RKEntityMapping.h>
-#import <RestKit/CoreData/RKFetchRequestManagedObjectCache.h>
-#import <RestKit/CoreData/RKInMemoryManagedObjectCache.h>
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
-#import <RestKit/CoreData/RKManagedObjectImporter.h>
-#import <RestKit/CoreData/RKManagedObjectMappingOperationDataSource.h>
-#import <RestKit/CoreData/RKManagedObjectStore.h>
-#import <RestKit/ObjectMapping.h>
+#import "ObjectMapping.h"
+#import "RKManagedObjectStore.h"
+#import "RKManagedObjectImporter.h"
+#import "RKManagedObjectMappingOperationDataSource.h"
+#import "RKEntityMapping.h"
+#import "RKManagedObjectCaching.h"
+#import "RKInMemoryManagedObjectCache.h"
+#import "RKFetchRequestManagedObjectCache.h"
-#import <RestKit/CoreData/NSManagedObject+RKAdditions.h>
-#import <RestKit/CoreData/NSManagedObjectContext+RKAdditions.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
+#import "RKPropertyInspector+CoreData.h"
+#import "NSManagedObjectContext+RKAdditions.h"
+#import "NSManagedObject+RKAdditions.h"
View
8 Code/CoreData/NSManagedObject+RKAdditions.m
@@ -6,10 +6,10 @@
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
-#import <RestKit/CoreData/NSManagedObject+RKAdditions.h>
-#import <RestKit/CoreData/NSManagedObjectContext+RKAdditions.h>
-#import <RestKit/CoreData/RKManagedObjectStore.h>
-#import <RestKit/Support/RKLog.h>
+#import "NSManagedObject+RKAdditions.h"
+#import "NSManagedObjectContext+RKAdditions.h"
+#import "RKLog.h"
+#import "RKManagedObjectStore.h"
@implementation NSManagedObject (RKAdditions)
View
4 Code/CoreData/NSManagedObjectContext+RKAdditions.m
@@ -18,9 +18,9 @@
// limitations under the License.
//
-#import <RestKit/CoreData/NSManagedObjectContext+RKAdditions.h>
-#import <RestKit/Support/RKLog.h>
#import <objc/runtime.h>
+#import "NSManagedObjectContext+RKAdditions.h"
+#import "RKLog.h"
@implementation NSManagedObjectContext (RKAdditions)
View
2 Code/CoreData/RKConnectionDescription.m
@@ -18,7 +18,7 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKConnectionDescription.h>
+#import "RKConnectionDescription.h"
static NSSet *RKSetWithInvalidAttributesForEntity(NSArray *attributes, NSEntityDescription *entity)
{
View
26 Code/CoreData/RKCoreData.h
@@ -1,26 +0,0 @@
-//
-// RKCoreData.h
-// RestKit
-//
-// Created by Samuel E. Giddins on 4/23/14.
-// Copyright (c) 2014 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.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef RestKit_RKCoreData_h
-#define RestKit_RKCoreData_h
-
-#import <RestKit/CoreData.h>
-
-#endif
View
58 Code/CoreData/RKEntityByAttributeCache.m
@@ -18,16 +18,12 @@
// limitations under the License.
//
-#if TARGET_OS_IPHONE
-#import <UIKit/UIKit.h>
-#endif
-
-#import <RestKit/CoreData/NSManagedObject+RKAdditions.h>
-#import <RestKit/CoreData/RKEntityByAttributeCache.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/ObjectMapping/RKPropertyInspector.h>
-#import <RestKit/Support/RKLog.h>
+#import "NSManagedObject+RKAdditions.h"
+#import "RKEntityByAttributeCache.h"
+#import "RKPropertyInspector+CoreData.h"
+#import "RKObjectUtilities.h"
+#import "RKPropertyInspector.h"
+#import "RKLog.h"
// Set Logging Component
#undef RKLogComponent
@@ -51,7 +47,7 @@ static id RKCacheKeyValueForEntityAttributeWithValue(NSEntityDescription *entity
id cacheKeyValue = RKCacheKeyValueForEntityAttributeWithValue(entity, attributeName, attributeValues[attributeName]);
[sortedValues addObject:cacheKeyValue];
};
-
+
return [sortedValues componentsJoinedByString:@":"];
}
@@ -104,23 +100,14 @@ - (instancetype)initWithEntity:(NSEntityDescription *)entity attributes:(NSArray
_attributes = attributeNames;
_managedObjectContext = context;
NSString *queueName = [[NSString alloc] initWithFormat:@"%@.%p", @"org.restkit.core-data.entity-by-attribute-cache", self];
- self.queue = dispatch_queue_create([queueName UTF8String], DISPATCH_QUEUE_CONCURRENT);
-
-#if TARGET_OS_IPHONE
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(didReceiveMemoryWarning:)
- name:UIApplicationDidReceiveMemoryWarningNotification
- object:nil];
-#endif
+ self.queue = dispatch_queue_create([queueName UTF8String], DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
- (void)dealloc
{
- [[NSNotificationCenter defaultCenter] removeObserver:self];
-
#if !OS_OBJECT_USE_OBJC
dispatch_release(_queue);
_queue = NULL;
@@ -173,7 +160,7 @@ - (void)load:(void (^)(void))completion
RKLogWarning(@"Failed to load entity cache. Failed to execute fetch request: %@", fetchRequest);
RKLogCoreDataError(error);
}
-
+
dispatch_barrier_async(self.queue, ^{
RKLogDebug(@"Loading entity cache for Entity '%@' by attributes '%@' in managed object context %@ (concurrencyType = %ld)",
self.entity.name, self.attributes, self.managedObjectContext, (unsigned long)self.managedObjectContext.concurrencyType);
@@ -183,7 +170,7 @@ - (void)load:(void (^)(void))completion
NSDictionary *attributeValues = [dictionary dictionaryWithValuesForKeys:self.attributes];
[self cacheObjectID:objectID forAttributeValues:attributeValues];
}
-
+
if (completion) dispatch_async(self.callbackQueue ?: dispatch_get_main_queue(), completion);
});
}];
@@ -211,17 +198,17 @@ - (NSManagedObject *)objectForObjectID:(NSManagedObjectID *)objectID inContext:(
{
/**
NOTE:
-
+
We use `existingObjectWithID:` as opposed to `objectWithID:` as `objectWithID:` can return us a fault
that will raise an exception when fired. `objectRegisteredForID:` is also an acceptable approach.
*/
__block NSError *error = nil;
__block NSManagedObject *object;
[context performBlockAndWait:^{
object = [context existingObjectWithID:objectID error:&error];
+ // Don't return the object if it has been deleted.
+ if ([object isDeleted]) object = nil;
}];
- // Don't return the object if it has been deleted.
- if ([object isDeleted]) object = nil;
if (! object) {
// Referential integrity errors often indicates that the temporary objectID does not exist in the specified context
if (error && !([objectID isTemporaryID] && [error code] == NSManagedObjectReferentialIntegrityError)) {
@@ -279,7 +266,7 @@ - (void)cacheObjectID:(NSManagedObjectID *)objectID forAttributeValues:(NSDictio
} else {
objectIDs = [NSMutableSet setWithObject:objectID];
}
-
+
if (nil == self.cacheKeysToObjectIDs) self.cacheKeysToObjectIDs = [NSMutableDictionary dictionary];
[self.cacheKeysToObjectIDs setValue:objectIDs forKey:cacheKey];
}
@@ -330,17 +317,17 @@ - (void)addObjects:(NSSet *)managedObjects completion:(void (^)(void))completion
entity = managedObject.entity;
objectID = [managedObject objectID];
attributeValues = [managedObject dictionaryWithValuesForKeys:self.attributes];
-
+
NSAssert([entity isKindOfEntity:self.entity], @"Cannot add object with entity '%@' to cache for entity of '%@'", [entity name], [self.entity name]);
newObjectIDsToAttributeValues[objectID] = attributeValues;
}
-
+
if ([newObjectIDsToAttributeValues count]) {
dispatch_barrier_async(self.queue, ^{
[newObjectIDsToAttributeValues enumerateKeysAndObjectsUsingBlock:^(NSManagedObjectID *objectID, NSDictionary *attributeValues, BOOL *stop) {
[self cacheObjectID:objectID forAttributeValues:attributeValues];
}];
-
+
if (completion) dispatch_async(self.callbackQueue ?: dispatch_get_main_queue(), completion);
});
} else {
@@ -365,17 +352,17 @@ - (void)removeObjects:(NSSet *)managedObjects completion:(void (^)(void))complet
entity = managedObject.entity;
objectID = [managedObject objectID];
attributeValues = [managedObject dictionaryWithValuesForKeys:self.attributes];
-
+
NSAssert([entity isKindOfEntity:self.entity], @"Cannot remove object with entity '%@' from cache for entity of '%@'", [entity name], [self.entity name]);
deletedObjectIDsToAttributeValues[objectID] = attributeValues;
}
-
+
if ([deletedObjectIDsToAttributeValues count]) {
dispatch_barrier_async(self.queue, ^{
[deletedObjectIDsToAttributeValues enumerateKeysAndObjectsUsingBlock:^(NSManagedObjectID *objectID, NSDictionary *attributeValues, BOOL *stop) {
[self deleteObjectID:objectID forAttributeValues:attributeValues];
}];
-
+
if (completion) dispatch_async(self.callbackQueue ?: dispatch_get_main_queue(), completion);
});
} else {
@@ -398,11 +385,6 @@ - (BOOL)containsObject:(NSManagedObject *)object
return [allObjectIDs containsObject:object.objectID];
}
-- (void)didReceiveMemoryWarning:(NSNotification *)notification
-{
- [self flush:nil];
-}
-
@end
@implementation RKEntityByAttributeCache (Deprecations)
View
18 Code/CoreData/RKEntityCache.h
@@ -155,6 +155,24 @@
*/
- (BOOL)containsObject:(NSManagedObject *)managedObject;
+/**
+ Call this before beginning a sequence of operations that require the cache not to be flushed.
+
+ This is used by RKInMemoryManagedObjectCache to workaround https://github.com/RestKit/RestKit/issues/1613 .
+
+ @see endAccessing
+ */
+- (void)beginAccessing;
+
+/**
+ Call this after completing a sequence of operations that require the cache not to be flushed.
+
+ This is used by RKInMemoryManagedObjectCache to workaround https://github.com/RestKit/RestKit/issues/1613 .
+
+ @see beginAccessing
+ */
+- (void)endAccessing;
+
@end
// Deprecated in v0.20.1
View
80 Code/CoreData/RKEntityCache.m
@@ -18,11 +18,19 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKEntityByAttributeCache.h>
-#import <RestKit/CoreData/RKEntityCache.h>
+#import <Foundation/Foundation.h>
+#if TARGET_OS_IPHONE
+#import <UIKit/UIKit.h>
+#endif
+
+#import "RKEntityByAttributeCache.h"
+#import "RKEntityCache.h"
@interface RKEntityCache ()
@property (nonatomic, strong) NSMutableSet *attributeCaches;
+@property (nonatomic, strong) NSLock *accessLock;
+@property (nonatomic, strong) NSMutableArray *pendingFlushCompletionBlocks;
+@property (nonatomic) NSInteger accessCount;
@end
@implementation RKEntityCache
@@ -34,6 +42,15 @@ - (instancetype)initWithManagedObjectContext:(NSManagedObjectContext *)context
if (self) {
_managedObjectContext = context;
_attributeCaches = [[NSMutableSet alloc] init];
+ _accessLock = [NSLock new];
+ _pendingFlushCompletionBlocks = [NSMutableArray new];
+
+#if TARGET_OS_IPHONE
+ [[NSNotificationCenter defaultCenter] addObserver:self
+ selector:@selector(didReceiveMemoryWarning:)
+ name:UIApplicationDidReceiveMemoryWarningNotification
+ object:nil];
+#endif
}
return self;
@@ -44,6 +61,11 @@ - (instancetype)init
return [self initWithManagedObjectContext:nil];
}
+- (void)dealloc
+{
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+}
+
- (void)cacheObjectsForEntity:(NSEntityDescription *)entity byAttributes:(NSArray *)attributeNames completion:(void (^)(void))completion
{
NSParameterAssert(entity);
@@ -122,18 +144,31 @@ - (NSSet *)attributeCachesForEntity:(NSEntityDescription *)entity
- (void)waitForDispatchGroup:(dispatch_group_t)dispatchGroup withCompletionBlock:(void (^)(void))completion
{
if (completion) {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
- dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER);
+ dispatch_group_notify(dispatchGroup, self.callbackQueue ?: dispatch_get_main_queue(), ^{
#if !OS_OBJECT_USE_OBJC
dispatch_release(dispatchGroup);
#endif
- dispatch_async(self.callbackQueue ?: dispatch_get_main_queue(), completion);
+ completion();
});
}
}
- (void)flush:(void (^)(void))completion
{
+ [_accessLock lock];
+ if (_accessCount == 0) {
+ [self _flushNow:^{
+ [_accessLock unlock];
+ if (completion) completion();
+ }];
+ } else {
+ [_pendingFlushCompletionBlocks addObject:completion ?: ^{}];
+ [_accessLock unlock];
+ }
+}
+
+- (void)_flushNow:(void (^)(void))completion
+{
dispatch_group_t dispatchGroup = completion ? dispatch_group_create() : NULL;
for (RKEntityByAttributeCache *cache in self.attributeCaches) {
if (dispatchGroup) dispatch_group_enter(dispatchGroup);
@@ -155,7 +190,7 @@ - (void)addObject:(NSManagedObject *)object completion:(void (^)(void))completio
[cache addObjects:objects completion:^{
if (dispatchGroup) dispatch_group_leave(dispatchGroup);
}];
- }
+ }
if (dispatchGroup) [self waitForDispatchGroup:dispatchGroup withCompletionBlock:completion];
}
@@ -223,8 +258,39 @@ - (BOOL)containsObject:(NSManagedObject *)managedObject
for (RKEntityByAttributeCache *attributeCache in [self attributeCachesForEntity:managedObject.entity]) {
if ([attributeCache containsObject:managedObject]) return YES;
}
-
+
return NO;
}
+- (void)beginAccessing
+{
+ [_accessLock lock];
+ _accessCount += 1;
+ [_accessLock unlock];
+}
+
+- (void)endAccessing
+{
+ [_accessLock lock];
+ _accessCount -= 1;
+ if (_accessCount == 0 && _pendingFlushCompletionBlocks.count > 0) {
+ [self _flushNow:^{
+ NSArray *blocks = [_pendingFlushCompletionBlocks copy];
+ [_pendingFlushCompletionBlocks removeAllObjects];
+ [_accessLock unlock];
+ for (dispatch_block_t block in blocks) {
+ block();
+ }
+ }];
+ } else {
+ [_accessLock unlock];
+ }
+
+}
+
+- (void)didReceiveMemoryWarning:(NSNotification *)notification
+{
+ [self flush:nil];
+}
+
@end
View
6 Code/CoreData/RKEntityMapping.h
@@ -19,9 +19,9 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/CoreData/RKConnectionDescription.h>
-#import <RestKit/ObjectMapping/RKObjectMapping.h>
-#import <RestKit/Support/RKMacros.h>
+#import "RKObjectMapping.h"
+#import "RKConnectionDescription.h"
+#import "RKMacros.h"
@class RKManagedObjectStore;
View
14 Code/CoreData/RKEntityMapping.m
@@ -18,13 +18,13 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKEntityMapping.h>
-#import <RestKit/CoreData/RKManagedObjectStore.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
-#import <RestKit/ObjectMapping/RKObjectMappingMatcher.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/ObjectMapping/RKRelationshipMapping.h>
-#import <RestKit/Support/RKLog.h>
+#import "RKEntityMapping.h"
+#import "RKManagedObjectStore.h"
+#import "RKObjectMappingMatcher.h"
+#import "RKPropertyInspector+CoreData.h"
+#import "RKLog.h"
+#import "RKRelationshipMapping.h"
+#import "RKObjectUtilities.h"
// Set Logging Component
#undef RKLogComponent
View
2 Code/CoreData/RKFetchRequestManagedObjectCache.h
@@ -18,7 +18,7 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
+#import "RKManagedObjectCaching.h"
/**
Provides a simple managed object cache strategy in which every request for an object
View
42 Code/CoreData/RKFetchRequestManagedObjectCache.m
@@ -18,11 +18,11 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKFetchRequestManagedObjectCache.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/ObjectMapping/RKPropertyInspector.h>
-#import <RestKit/Support/RKLog.h>
+#import "RKFetchRequestManagedObjectCache.h"
+#import "RKLog.h"
+#import "RKPropertyInspector.h"
+#import "RKPropertyInspector+CoreData.h"
+#import "RKObjectUtilities.h"
// Set Logging Component
#undef RKLogComponent
@@ -43,15 +43,31 @@
return [keyFragments componentsJoinedByString:@":"];
}
-// NOTE: We build a dynamic format string here because `NSCompoundPredicate` does not support use of substiution variables
-static NSPredicate *RKPredicateWithSubsitutionVariablesForAttributeValues(NSDictionary *attributeValues)
+// NOTE: We make sure to convert the attribute values to compatible names that can be replaced correctly by `predicateWithSubstitutionVariables`
+static NSString *RKAttributePlaceholderForAttributeName(NSString *attributeName)
+{
+ return [[attributeName componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet]] componentsJoinedByString:@"_"];
+}
+
+static NSDictionary *RKSubstitutionVariablesForAttributeValues(NSDictionary *attributeValues)
+{
+ NSMutableDictionary *placeholders = [[NSMutableDictionary alloc] initWithCapacity:attributeValues.count];
+ [attributeValues enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
+ placeholders[RKAttributePlaceholderForAttributeName(key)] = value;
+ }];
+
+ return [NSDictionary dictionaryWithDictionary:placeholders];
+}
+
+// NOTE: We build a dynamic format string here because `NSCompoundPredicate` does not support use of substitution variables
+static NSPredicate *RKPredicateWithSubstitutionVariablesForAttributeValues(NSDictionary *attributeValues)
{
NSArray *attributeNames = [attributeValues allKeys];
NSMutableArray *formatFragments = [NSMutableArray arrayWithCapacity:[attributeNames count]];
[attributeValues enumerateKeysAndObjectsUsingBlock:^(NSString *attributeName, id value, BOOL *stop) {
NSString *formatFragment = RKObjectIsCollection(value)
- ? [NSString stringWithFormat:@"%@ IN $%@", attributeName, attributeName]
- : [NSString stringWithFormat:@"%@ = $%@", attributeName, attributeName];
+ ? [NSString stringWithFormat:@"%@ IN $%@", attributeName, RKAttributePlaceholderForAttributeName(attributeName)]
+ : [NSString stringWithFormat:@"%@ = $%@", attributeName, RKAttributePlaceholderForAttributeName(attributeName)];
[formatFragments addObject:formatFragment];
}];
@@ -103,16 +119,18 @@ - (NSSet *)managedObjectsWithEntity:(NSEntityDescription *)entity
dispatch_sync(self.cacheQueue, ^{
substitutionPredicate = (self.predicateCache)[predicateCacheKey];
});
-
+
+ NSDictionary *substitutionVariables = RKSubstitutionVariablesForAttributeValues(attributeValues);
+
if (! substitutionPredicate) {
- substitutionPredicate = RKPredicateWithSubsitutionVariablesForAttributeValues(attributeValues);
+ substitutionPredicate = RKPredicateWithSubstitutionVariablesForAttributeValues(attributeValues);
dispatch_barrier_async(self.cacheQueue, ^{
(self.predicateCache)[predicateCacheKey] = substitutionPredicate;
});
}
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[entity name]];
- fetchRequest.predicate = [substitutionPredicate predicateWithSubstitutionVariables:attributeValues];
+ fetchRequest.predicate = [substitutionPredicate predicateWithSubstitutionVariables:substitutionVariables];
__block NSError *error = nil;
__block NSArray *objects = nil;
[managedObjectContext performBlockAndWait:^{
View
2 Code/CoreData/RKInMemoryManagedObjectCache.h
@@ -18,7 +18,7 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
+#import "RKManagedObjectCaching.h"
/**
Provides a fast managed object cache where-in object instances are retained in memory to avoid hitting the Core Data persistent store. Performance is greatly increased over fetch request based strategy at the expense of memory consumption.
View
13 Code/CoreData/RKInMemoryManagedObjectCache.m
@@ -18,10 +18,10 @@
// limitations under the License.
//
-#import <RestKit/CoreData/RKEntityByAttributeCache.h>
-#import <RestKit/CoreData/RKEntityCache.h>
-#import <RestKit/CoreData/RKInMemoryManagedObjectCache.h>
-#import <RestKit/Support/RKLog.h>
+#import "RKInMemoryManagedObjectCache.h"
+#import "RKEntityCache.h"
+#import "RKLog.h"
+#import "RKEntityByAttributeCache.h"
// Set Logging Component
#undef RKLogComponent
@@ -90,6 +90,7 @@ - (NSSet *)managedObjectsWithEntity:(NSEntityDescription *)entity
NSParameterAssert(managedObjectContext);
NSArray *attributes = [attributeValues allKeys];
+ [self.entityCache beginAccessing];
if (! [self.entityCache isEntity:entity cachedByAttributes:attributes]) {
RKLogInfo(@"Caching instances of Entity '%@' by attributes '%@'", entity.name, [attributes componentsJoinedByString:@", "]);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
@@ -127,7 +128,9 @@ - (NSSet *)managedObjectsWithEntity:(NSEntityDescription *)entity
RKLogTrace(@"Cached %ld objects", (long)[attributeCache count]);
}
- return [self.entityCache objectsForEntity:entity withAttributeValues:attributeValues inContext:managedObjectContext];
+ NSSet *result = [self.entityCache objectsForEntity:entity withAttributeValues:attributeValues inContext:managedObjectContext];
+ [self.entityCache endAccessing];
+ return result;
}
- (void)didFetchObject:(NSManagedObject *)object
View
16 Code/CoreData/RKManagedObjectImporter.m
@@ -22,14 +22,14 @@
#import <MobileCoreServices/UTType.h>
#endif
-#import <RestKit/CoreData/RKFetchRequestManagedObjectCache.h>
-#import <RestKit/CoreData/RKInMemoryManagedObjectCache.h>
-#import <RestKit/CoreData/RKManagedObjectImporter.h>
-#import <RestKit/CoreData/RKManagedObjectMappingOperationDataSource.h>
-#import <RestKit/ObjectMapping/RKMapperOperation.h>
-#import <RestKit/Support/RKLog.h>
-#import <RestKit/Support/RKMIMETypeSerialization.h>
-#import <RestKit/Support/RKPathUtilities.h>
+#import "RKManagedObjectImporter.h"
+#import "RKMapperOperation.h"
+#import "RKManagedObjectMappingOperationDataSource.h"
+#import "RKInMemoryManagedObjectCache.h"
+#import "RKFetchRequestManagedObjectCache.h"
+#import "RKMIMETypeSerialization.h"
+#import "RKPathUtilities.h"
+#import "RKLog.h"
// Set Logging Component
#undef RKLogComponent
View
2 Code/CoreData/RKManagedObjectMappingOperationDataSource.h
@@ -19,7 +19,7 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/ObjectMapping/RKMappingOperationDataSource.h>
+#import "RKMappingOperationDataSource.h"
@protocol RKManagedObjectCaching;
View
28 Code/CoreData/RKManagedObjectMappingOperationDataSource.m
@@ -18,21 +18,21 @@
// limitations under the License.
//
-#import <RKValueTransformers/RKValueTransformers.h>
-#import <RestKit/CoreData/NSManagedObject+RKAdditions.h>
-#import <RestKit/CoreData/RKEntityMapping.h>
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
-#import <RestKit/CoreData/RKManagedObjectMappingOperationDataSource.h>
-#import <RestKit/CoreData/RKManagedObjectStore.h>
-#import <RestKit/CoreData/RKRelationshipConnectionOperation.h>
-#import <RestKit/ObjectMapping/RKMappingErrors.h>
-#import <RestKit/ObjectMapping/RKMappingOperation.h>
-#import <RestKit/ObjectMapping/RKObjectMapping.h>
-#import <RestKit/ObjectMapping/RKObjectMappingMatcher.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/ObjectMapping/RKRelationshipMapping.h>
-#import <RestKit/Support/RKLog.h>
#import <objc/runtime.h>
+#import "RKManagedObjectMappingOperationDataSource.h"
+#import "RKObjectMapping.h"
+#import "RKEntityMapping.h"
+#import "RKLog.h"
+#import "RKManagedObjectStore.h"
+#import "RKMappingOperation.h"
+#import "RKObjectMappingMatcher.h"
+#import "RKManagedObjectCaching.h"
+#import "RKRelationshipConnectionOperation.h"
+#import "RKMappingErrors.h"
+#import "RKValueTransformers.h"
+#import "RKRelationshipMapping.h"
+#import "RKObjectUtilities.h"
+#import "NSManagedObject+RKAdditions.h"
extern NSString * const RKObjectMappingNestingAttributeKeyName;
View
4 Code/CoreData/RKManagedObjectStore.h
@@ -19,8 +19,8 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/CoreData/RKEntityMapping.h>
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
+#import "RKEntityMapping.h"
+#import "RKManagedObjectCaching.h"
@class RKManagedObjectStore;
View
18 Code/CoreData/RKManagedObjectStore.m
@@ -18,15 +18,15 @@
// limitations under the License.
//
-#import <RestKit/CoreData/NSManagedObjectContext+RKAdditions.h>
-#import <RestKit/CoreData/RKFetchRequestManagedObjectCache.h>
-#import <RestKit/CoreData/RKInMemoryManagedObjectCache.h>
-#import <RestKit/CoreData/RKManagedObjectStore.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
-#import <RestKit/ObjectMapping/RKPropertyInspector.h>
-#import <RestKit/Support/RKLog.h>
-#import <RestKit/Support/RKPathUtilities.h>
#import <objc/runtime.h>
+#import "RKManagedObjectStore.h"
+#import "RKLog.h"
+#import "RKPropertyInspector.h"
+#import "RKPropertyInspector+CoreData.h"
+#import "RKPathUtilities.h"
+#import "RKInMemoryManagedObjectCache.h"
+#import "RKFetchRequestManagedObjectCache.h"
+#import "NSManagedObjectContext+RKAdditions.h"
// Set Logging Component
#undef RKLogComponent
@@ -359,8 +359,6 @@ - (void)createManagedObjectContexts
- (void)recreateManagedObjectContexts
{
- [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:self.persistentStoreManagedObjectContext];
-
self.persistentStoreManagedObjectContext = nil;
self.mainQueueManagedObjectContext = nil;
[self createManagedObjectContexts];
View
2 Code/CoreData/RKPropertyInspector+CoreData.h
@@ -18,7 +18,7 @@
// limitations under the License.
//
-#import <RestKit/ObjectMapping/RKPropertyInspector.h>
+#import "RKPropertyInspector.h"
/**
The `CoreData` category augments the `RKPropertyInspector` class with support for introspecting the property types for `NSManagedObject` and `NSEntityDescription` objects.
View
8 Code/CoreData/RKPropertyInspector+CoreData.m
@@ -19,11 +19,11 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/CoreData/RKPropertyInspector+CoreData.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/Support/RKLog.h>
-#import <RestKit/Support/RKMacros.h>
#import <objc/message.h>
+#import "RKPropertyInspector+CoreData.h"
+#import "RKLog.h"
+#import "RKObjectUtilities.h"
+#import "RKMacros.h"
// Set Logging Component
#undef RKLogComponent
View
16 Code/CoreData/RKRelationshipConnectionOperation.m
@@ -19,14 +19,14 @@
//
#import <CoreData/CoreData.h>
-#import <RestKit/CoreData/RKConnectionDescription.h>
-#import <RestKit/CoreData/RKEntityMapping.h>
-#import <RestKit/CoreData/RKManagedObjectCaching.h>
-#import <RestKit/CoreData/RKRelationshipConnectionOperation.h>
-#import <RestKit/ObjectMapping/RKObjectMappingMatcher.h>
-#import <RestKit/ObjectMapping/RKObjectUtilities.h>
-#import <RestKit/Support/RKErrors.h>
-#import <RestKit/Support/RKLog.h>
+#import "RKRelationshipConnectionOperation.h"
+#import "RKConnectionDescription.h"
+#import "RKEntityMapping.h"
+#import "RKLog.h"
+#import "RKManagedObjectCaching.h"
+#import "RKObjectMappingMatcher.h"
+#import "RKErrors.h"
+#import "RKObjectUtilities.h"
// Set Logging Component
#undef RKLogComponent
View
24 Code/Network.h
@@ -18,17 +18,17 @@
// limitations under the License.
//
-#import <RestKit/Network/RKObjectManager.h>
-#import <RestKit/Network/RKObjectParameterization.h>
-#import <RestKit/Network/RKObjectRequestOperation.h>
-#import <RestKit/Network/RKPathMatcher.h>
-#import <RestKit/Network/RKRequestDescriptor.h>
-#import <RestKit/Network/RKResponseDescriptor.h>
-#import <RestKit/Network/RKRoute.h>
-#import <RestKit/Network/RKRouteSet.h>
-#import <RestKit/Network/RKRouter.h>
-#import <RestKit/ObjectMapping/RKHTTPUtilities.h>
+#import "RKRoute.h"
+#import "RKRouteSet.h"
+#import "RKRouter.h"
+#import "RKRequestDescriptor.h"
+#import "RKResponseDescriptor.h"
+#import "RKObjectManager.h"
+#import "RKHTTPUtilities.h"
+#import "RKObjectRequestOperation.h"
+#import "RKObjectParameterization.h"
+#import "RKPathMatcher.h"
-#ifdef _COREDATADEFINES_H
-#import <RestKit/Network/RKManagedObjectRequestOperation.h>
+#if __has_include("CoreData.h")
+#import "RKManagedObjectRequestOperation.h"
#endif
View
651 Code/Network/AFNetworking/AFRKHTTPClient.h
@@ -0,0 +1,651 @@
+// AFHTTPClient.h
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import "AFRKURLConnectionOperation.h"
+
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <SystemConfiguration/SystemConfiguration.h>
+#import <MobileCoreServices/MobileCoreServices.h>
+#import <Security/Security.h>
+#else
+#import <SystemConfiguration/SystemConfiguration.h>
+#import <CoreServices/CoreServices.h>
+#import <Security/Security.h>
+#endif
+
+/**
+ `AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
+
+ ## Automatic Content Parsing
+
+ Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
+
+ ## Subclassing Notes
+
+ In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
+
+ ## Methods to Override
+
+ To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
+
+ To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
+
+ ## Default Headers
+
+ By default, `AFHTTPClient` sets the following HTTP headers:
+
+ - `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
+ - `User-Agent: (generated user agent)`
+
+ You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
+
+ ## URL Construction Using Relative Paths
+
+ Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
+
+ NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+ [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
+ [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
+ [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
+ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
+
+ ## NSCoding / NSCopying Conformance
+
+ `AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
+
+ - Archives and copies of HTTP clients will be initialized with an empty operation queue.
+ - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
+ */
+
+#ifdef _SYSTEMCONFIGURATION_H
+typedef enum {
+ AFRKNetworkReachabilityStatusUnknown = -1,
+ AFRKNetworkReachabilityStatusNotReachable = 0,
+ AFRKNetworkReachabilityStatusReachableViaWWAN = 1,
+ AFRKNetworkReachabilityStatusReachableViaWiFi = 2,
+} AFRKNetworkReachabilityStatus;
+#else
+#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.")
+#endif
+
+#ifndef __UTTYPE__
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
+#else
+#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
+#endif
+#endif
+
+typedef enum {
+ AFRKFormURLParameterEncoding,
+ AFRKJSONParameterEncoding,
+ AFRKPropertyListParameterEncoding,
+} AFRKHTTPClientParameterEncoding;
+
+@class AFRKHTTPRequestOperation;
+@protocol AFRKMultipartFormData;
+
+@interface AFRKHTTPClient : NSObject <NSCoding, NSCopying>
+
+///---------------------------------------
+/// @name Accessing HTTP Client Properties
+///---------------------------------------
+
+/**
+ The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
+ */
+@property (readonly, nonatomic, strong) NSURL *baseURL;
+
+/**
+ The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+/**
+ The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default.
+
+ @warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
+ */
+@property (nonatomic, assign) AFRKHTTPClientParameterEncoding parameterEncoding;
+
+/**
+ The operation queue which manages operations enqueued by the HTTP client.
+ */
+@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
+
+/**
+ The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
+
+ @warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+@property (readonly, nonatomic, assign) AFRKNetworkReachabilityStatus networkReachabilityStatus;
+#endif
+
+/**
+ Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`.
+ */
+@property (nonatomic, assign) AFRKURLConnectionOperationSSLPinningMode defaultSSLPinningMode;
+
+/**
+ Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate.
+
+ If `_AFRKNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
+ */
+@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
+
+///---------------------------------------------
+/// @name Creating and Initializing HTTP Clients
+///---------------------------------------------
+
+/**
+ Creates and initializes an `AFHTTPClient` object with the specified base URL.
+
+ @param url The base URL for the HTTP client. This argument must not be `nil`.
+
+ @return The newly-initialized HTTP client
+ */
++ (instancetype)clientWithBaseURL:(NSURL *)url;
+
+/**
+ Initializes an `AFHTTPClient` object with the specified base URL.
+
+ This is the designated initializer.
+
+ @param url The base URL for the HTTP client. This argument must not be `nil`.
+
+ @return The newly-initialized HTTP client
+ */
+- (id)initWithBaseURL:(NSURL *)url;
+
+///-----------------------------------
+/// @name Managing Reachability Status
+///-----------------------------------
+
+/**
+ Sets a callback to be executed when the network availability of the `baseURL` host changes.
+
+ @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
+
+ @warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFRKNetworkReachabilityStatus status))block;
+#endif
+
+///-------------------------------
+/// @name Managing HTTP Operations
+///-------------------------------
+
+/**
+ Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
+
+ When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
+
+ @param operationClass The subclass of `AFHTTPRequestOperation` to register
+
+ @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
+ */
+- (BOOL)registerHTTPOperationClass:(Class)operationClass;
+
+/**
+ Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
+
+ @param operationClass The subclass of `AFHTTPRequestOperation` to register
+ */
+- (void)unregisterHTTPOperationClass:(Class)operationClass;
+
+///----------------------------------
+/// @name Managing HTTP Header Values
+///----------------------------------
+
+/**
+ Returns the value for the HTTP headers set in request objects created by the HTTP client.
+
+ @param header The HTTP header to return the default value for
+
+ @return The default value for the HTTP header, or `nil` if unspecified
+ */
+- (NSString *)defaultValueForHeader:(NSString *)header;
+
+/**
+ Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
+
+ @param header The HTTP header to set a default value for
+ @param value The value set as default for the specified header, or `nil
+ */
+- (void)setDefaultHeader:(NSString *)header
+ value:(NSString *)value;
+
+/**
+ Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
+
+ @param username The HTTP basic auth username
+ @param password The HTTP basic auth password
+ */
+- (void)setAuthorizationHeaderWithUsername:(NSString *)username
+ password:(NSString *)password;
+
+/**
+ Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
+
+ @param token The authentication token
+ */
+- (void)setAuthorizationHeaderWithToken:(NSString *)token;
+
+
+/**
+ Clears any existing value for the "Authorization" HTTP header.
+ */
+- (void)clearAuthorizationHeader;
+
+///-------------------------------
+/// @name Managing URL Credentials
+///-------------------------------
+
+/**
+ Set the default URL credential to be set for request operations.
+
+ @param credential The URL credential
+ */
+- (void)setDefaultCredential:(NSURLCredential *)credential;
+
+///-------------------------------
+/// @name Creating Request Objects
+///-------------------------------
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
+
+ If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
+
+ @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
+ @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters;
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
+
+ Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
+
+ @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFRKMultipartFormData> formData))block;
+
+///-------------------------------
+/// @name Creating HTTP Operations
+///-------------------------------
+
+/**
+ Creates an `AFHTTPRequestOperation`.
+
+ In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
+
+ @param urlRequest The request object to be loaded asynchronously during execution of the operation.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
+ */
+- (AFRKHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+
+///----------------------------------------
+/// @name Managing Enqueued HTTP Operations
+///----------------------------------------
+
+/**
+ Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
+
+ @param operation The HTTP request operation to be enqueued.
+ */
+- (void)enqueueHTTPRequestOperation:(AFRKHTTPRequestOperation *)operation;
+
+/**
+ Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
+
+ This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
+
+ @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
+ @param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
+ */
+- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
+
+///---------------------------------------
+/// @name Batching HTTP Request Operations
+///---------------------------------------
+
+/**
+ Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
+
+ Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
+
+ @param urlRequests The `NSURLRequest` objects used to create and enqueue operations.
+ @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
+ @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
+ */
+- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock;
+
+/**
+ Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
+
+ @param operations The request operations used to be batched and enqueued.
+ @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
+ @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
+ */
+- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and appended as the query string for the request URL.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)getPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)postPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)putPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and appended as the query string for the request URL.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)deletePath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)patchPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFRKHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFRKHTTPRequestOperation *operation, NSError *error))failure;
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Network Reachability
+
+ The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
+
+ enum {
+ AFNetworkReachabilityStatusUnknown,
+ AFNetworkReachabilityStatusNotReachable,
+ AFNetworkReachabilityStatusReachableViaWWAN,
+ AFNetworkReachabilityStatusReachableViaWiFi,
+ }
+
+ `AFNetworkReachabilityStatusUnknown`
+ The `baseURL` host reachability is not known.
+
+ `AFNetworkReachabilityStatusNotReachable`
+ The `baseURL` host cannot be reached.
+
+ `AFNetworkReachabilityStatusReachableViaWWAN`
+ The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
+
+ `AFNetworkReachabilityStatusReachableViaWiFi`
+ The `baseURL` host can be reached via a Wi-Fi connection.
+
+ ### Keys for Notification UserInfo Dictionary
+
+ Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
+
+ `AFNetworkingReachabilityNotificationStatusItem`
+ A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
+ The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
+
+ ## Parameter Encoding
+
+ The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
+
+ enum {
+ AFFormURLParameterEncoding,
+ AFJSONParameterEncoding,
+ AFPropertyListParameterEncoding,
+ }
+
+ `AFFormURLParameterEncoding`
+ Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
+
+ `AFJSONParameterEncoding`
+ Parameters are encoded into JSON in the message body.
+
+ `AFPropertyListParameterEncoding`
+ Parameters are encoded into a property list in the message body.
+ */
+
+///----------------
+/// @name Functions
+///----------------
+
+/**
+ Returns a query string constructed by a set of parameters, using the specified encoding.
+
+ Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
+
+ If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
+
+ @param parameters The parameters used to construct the query string
+ @param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
+
+ @return A percent-escaped query string
+ */
+extern NSString * AFRKQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when network reachability changes.
+ This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
+
+ @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+extern NSString * const AFRKNetworkingReachabilityDidChangeNotification;
+extern NSString * const AFRKNetworkingReachabilityNotificationStatusItem;
+#endif
+
+#pragma mark -
+
+extern NSUInteger const kAFRKUploadStream3GSuggestedPacketSize;
+extern NSTimeInterval const kAFRKUploadStream3GSuggestedDelay;
+
+/**
+ The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
+ */
+@protocol AFRKMultipartFormData
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
+
+ The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
+
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
+
+ @return `YES` if the file data was successfully appended, otherwise `NO`.
+ */
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+ name:(NSString *)name
+ error:(NSError * __autoreleasing *)error;
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
+
+ @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
+ @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
+
+ @return `YES` if the file data was successfully appended otherwise `NO`.
+ */
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+ name:(NSString *)name
+ fileName:(NSString *)fileName
+ mimeType:(NSString *)mimeType
+ error:(NSError * __autoreleasing *)error;
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
+
+ @param inputStream The input stream to be appended to the form data
+ @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
+ @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
+ @param length The length of the specified input stream in bytes.
+ @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
+ */
+- (void)appendPartWithInputStream:(NSInputStream *)inputStream
+ name:(NSString *)name
+ fileName:(NSString *)fileName
+ length:(unsigned long long)length
+ mimeType:(NSString *)mimeType;
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
+ @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
+ */
+- (void)appendPartWithFileData:(NSData *)data
+ name:(NSString *)name
+ fileName:(NSString *)fileName
+ mimeType:(NSString *)mimeType;
+
+/**
+ Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ */
+
+- (void)appendPartWithFormData:(NSData *)data
+ name:(NSString *)name;
+
+
+/**
+ Appends HTTP headers, followed by the encoded data and the multipart form boundary.
+
+ @param headers The HTTP headers to be appended to the form data.
+ @param body The data to be encoded and appended to the form data.
+ */
+- (void)appendPartWithHeaders:(NSDictionary *)headers
+ body:(NSData *)body;
+
+/**
+ Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
+
+ When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFRKUploadStream3GSuggestedPacketSize` and `kAFRKUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
+
+ @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
+ @param delay Duration of delay each time a packet is read. By default, no delay is set.
+ */
+- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
+ delay:(NSTimeInterval)delay;
+
+@end
View
1,403 Code/Network/AFNetworking/AFRKHTTPClient.m
@@ -0,0 +1,1403 @@
+// AFHTTPClient.m
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import "AFRKHTTPClient.h"
+#import "AFRKHTTPRequestOperation.h"
+
+#import <Availability.h>
+
+#ifdef _SYSTEMCONFIGURATION_H
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+#endif
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+#ifdef _SYSTEMCONFIGURATION_H
+NSString * const AFRKNetworkingReachabilityDidChangeNotification = @"com.restkit.alamofire.networking.reachability.change";
+NSString * const AFRKNetworkingReachabilityNotificationStatusItem = @"AFRKNetworkingReachabilityNotificationStatusItem";
+
+typedef SCNetworkReachabilityRef AFRKNetworkReachabilityRef;
+typedef void (^AFRKNetworkReachabilityStatusBlock)(AFRKNetworkReachabilityStatus status);
+#else
+typedef id AFRKNetworkReachabilityRef;
+#endif
+
+typedef void (^AFRKCompletionBlock)(void);
+
+static NSString * AFRKBase64EncodedStringFromString(NSString *string) {
+ NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
+ NSUInteger length = [data length];
+ NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
+
+ uint8_t *input = (uint8_t *)[data bytes];
+ uint8_t *output = (uint8_t *)[mutableData mutableBytes];
+
+ for (NSUInteger i = 0; i < length; i += 3) {
+ NSUInteger value = 0;
+ for (NSUInteger j = i; j < (i + 3); j++) {
+ value <<= 8;
+ if (j < length) {
+ value |= (0xFF & input[j]);
+ }
+ }
+
+ static uint8_t const kAFRKBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ NSUInteger idx = (i / 3) * 4;
+ output[idx + 0] = kAFRKBase64EncodingTable[(value >> 18) & 0x3F];
+ output[idx + 1] = kAFRKBase64EncodingTable[(value >> 12) & 0x3F];
+ output[idx + 2] = (i + 1) < length ? kAFRKBase64EncodingTable[(value >> 6) & 0x3F] : '=';
+ output[idx + 3] = (i + 2) < length ? kAFRKBase64EncodingTable[(value >> 0) & 0x3F] : '=';
+ }
+
+ return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
+}
+
+static NSString * const kAFRKCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";
+
+static NSString * AFRKPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
+ static NSString * const kAFRKCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";
+
+ return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFRKCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFRKCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
+}
+
+static NSString * AFRKPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
+ return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFRKCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
+}
+
+#pragma mark -
+
+@interface AFRKQueryStringPair : NSObject
+@property (readwrite, nonatomic, strong) id field;
+@property (readwrite, nonatomic, strong) id value;
+
+- (id)initWithField:(id)field value:(id)value;
+
+- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
+@end
+
+@implementation AFRKQueryStringPair
+@synthesize field = _field;
+@synthesize value = _value;
+
+- (id)initWithField:(id)field value:(id)value {
+ self = [super init];
+ if (!self) {
+ return nil;
+ }
+
+ self.field = field;
+ self.value = value;
+
+ return self;
+}
+
+- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
+ if (!self.value || [self.value isEqual:[NSNull null]]) {
+ return AFRKPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding);
+ } else {
+ return [NSString stringWithFormat:@"%@=%@", AFRKPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFRKPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)];
+ }
+}
+
+@end
+
+#pragma mark -
+
+extern NSArray * AFRKQueryStringPairsFromDictionary(NSDictionary *dictionary);
+extern NSArray * AFRKQueryStringPairsFromKeyAndValue(NSString *key, id value);
+
+NSString * AFRKQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
+ NSMutableArray *mutablePairs = [NSMutableArray array];
+ for (AFRKQueryStringPair *pair in AFRKQueryStringPairsFromDictionary(parameters)) {
+ [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
+ }
+
+ return [mutablePairs componentsJoinedByString:@"&"];
+}
+
+NSArray * AFRKQueryStringPairsFromDictionary(NSDictionary *dictionary) {
+ return AFRKQueryStringPairsFromKeyAndValue(nil, dictionary);
+}
+
+NSArray * AFRKQueryStringPairsFromKeyAndValue(NSString *key, id value) {
+ NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
+
+ if ([value isKindOfClass:[NSDictionary class]]) {
+ NSDictionary *dictionary = value;
+ // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
+ NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)];
+ for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
+ id nestedValue = [dictionary objectForKey:nestedKey];
+ if (nestedValue) {
+ [mutableQueryStringComponents addObjectsFromArray:AFRKQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
+ }
+ }
+ } else if ([value isKindOfClass:[NSArray class]]) {
+ NSArray *array = value;
+ for (id nestedValue in array) {
+ [mutableQueryStringComponents addObjectsFromArray:AFRKQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
+ }
+ } else if ([value isKindOfClass:[NSSet class]]) {
+ NSSet *set = value;
+ for (id obj in set) {
+ [mutableQueryStringComponents addObjectsFromArray:AFRKQueryStringPairsFromKeyAndValue(key, obj)];
+ }
+ } else {
+ [mutableQueryStringComponents addObject:[[AFRKQueryStringPair alloc] initWithField:key value:value]];
+ }
+
+ return mutableQueryStringComponents;
+}
+
+@interface AFRKStreamingMultipartFormData : NSObject <AFRKMultipartFormData>
+- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
+ stringEncoding:(NSStringEncoding)encoding;
+
+- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
+@end
+
+#pragma mark -
+
+@interface AFRKHTTPClient ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@property (readwrite, nonatomic, strong) NSMutableArray *registeredHTTPOperationClassNames;
+@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
+@property (readwrite, nonatomic, strong) NSURLCredential *defaultCredential;
+@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
+#ifdef _SYSTEMCONFIGURATION_H
+@property (readwrite, nonatomic, assign) AFRKNetworkReachabilityRef networkReachability;
+@property (readwrite, nonatomic, assign) AFRKNetworkReachabilityStatus networkReachabilityStatus;
+@property (readwrite, nonatomic, copy) AFRKNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
+#endif
+
+#ifdef _SYSTEMCONFIGURATION_H
+- (void)startMonitoringNetworkReachability;
+- (void)stopMonitoringNetworkReachability;
+#endif
+@end
+
+@implementation AFRKHTTPClient