appjam 0.1.8.6 → 0.1.8.7

Sign up to get free protection for your applications and to get access to all the features.
Files changed (86) hide show
  1. data/lib/appjam.rb +1 -1
  2. data/lib/appjam/generators/blank.rb +133 -0
  3. data/lib/appjam/generators/help.rb +5 -3
  4. data/lib/appjam/generators/templates/blank/EiffelApplication.xcodeproj/project.pbxproj +855 -0
  5. data/lib/appjam/generators/templates/blank/EiffelApplication.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
  6. data/lib/appjam/generators/templates/blank/EiffelApplication.xcodeproj/project.xcworkspace/xcuserdata/eiffel.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  7. data/lib/appjam/generators/templates/blank/EiffelApplication.xcodeproj/xcuserdata/eiffel.xcuserdatad/xcschemes/EiffelApplication.xcscheme +96 -0
  8. data/lib/appjam/generators/templates/blank/EiffelApplication.xcodeproj/xcuserdata/eiffel.xcuserdatad/xcschemes/xcschememanagement.plist +27 -0
  9. data/lib/appjam/generators/templates/blank/EiffelApplication/AppDelegate.h.tt +22 -0
  10. data/lib/appjam/generators/templates/blank/EiffelApplication/AppDelegate.m.tt +156 -0
  11. data/lib/appjam/generators/templates/blank/EiffelApplication/EiffelApplication-Info.plist +45 -0
  12. data/lib/appjam/generators/templates/blank/EiffelApplication/EiffelApplication-Prefix.pch.tt +30 -0
  13. data/lib/appjam/generators/templates/blank/EiffelApplication/en.lproj/InfoPlist.strings +2 -0
  14. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFHTTPClient.h +636 -0
  15. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFHTTPClient.m +1359 -0
  16. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFHTTPRequestOperation.h +133 -0
  17. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFHTTPRequestOperation.m +318 -0
  18. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFImageRequestOperation.h +108 -0
  19. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFImageRequestOperation.m +234 -0
  20. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFJSONRequestOperation.h +71 -0
  21. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFJSONRequestOperation.m +142 -0
  22. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFNetworkActivityIndicatorManager.h +75 -0
  23. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFNetworkActivityIndicatorManager.m +145 -0
  24. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFNetworking.h +43 -0
  25. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFPropertyListRequestOperation.h +68 -0
  26. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFPropertyListRequestOperation.m +142 -0
  27. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFURLConnectionOperation.h +379 -0
  28. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFURLConnectionOperation.m +818 -0
  29. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFXMLRequestOperation.h +89 -0
  30. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/AFXMLRequestOperation.m +166 -0
  31. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/UIImageView+AFNetworking.h +78 -0
  32. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/AFNetworking/UIImageView+AFNetworking.m +184 -0
  33. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/JSONKit/JSONKit.h +251 -0
  34. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/JSONKit/JSONKit.m +3067 -0
  35. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabase.h +155 -0
  36. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabase.m +1162 -0
  37. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabaseAdditions.h +37 -0
  38. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabaseAdditions.m +163 -0
  39. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabasePool.h +75 -0
  40. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabasePool.m +244 -0
  41. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabaseQueue.h +38 -0
  42. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMDatabaseQueue.m +176 -0
  43. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMResultSet.h +104 -0
  44. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/frameworks/fmdb/FMResultSet.m +413 -0
  45. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/EGOCache/EGOCache.h +78 -0
  46. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/EGOCache/EGOCache.m +370 -0
  47. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDASLLogger.h +41 -0
  48. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDASLLogger.m +99 -0
  49. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDAbstractDatabaseLogger.h +102 -0
  50. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDAbstractDatabaseLogger.m +727 -0
  51. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDFileLogger.h +334 -0
  52. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDFileLogger.m +1353 -0
  53. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDLog.h +601 -0
  54. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDLog.m +1083 -0
  55. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDTTYLogger.h +167 -0
  56. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/DDTTYLogger.m +1479 -0
  57. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/Extensions/ContextFilterLogFormatter.h +65 -0
  58. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/Extensions/ContextFilterLogFormatter.m +191 -0
  59. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/Extensions/DispatchQueueLogFormatter.h +116 -0
  60. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Lumberjack/Extensions/DispatchQueueLogFormatter.m +251 -0
  61. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/ObjectiveMixin/Mixin.h +33 -0
  62. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/ObjectiveMixin/Mixin.m +122 -0
  63. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/USArrayWrapper.h +72 -0
  64. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/USArrayWrapper.m +305 -0
  65. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/USConstants.h +38 -0
  66. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/USDictionaryWrapper.h +57 -0
  67. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/USDictionaryWrapper.m +188 -0
  68. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/Underscore+Functional.h +89 -0
  69. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/Underscore+Functional.m +261 -0
  70. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/Underscore-Prefix.pch +7 -0
  71. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/Underscore.h +50 -0
  72. data/lib/appjam/generators/templates/blank/EiffelApplication/libs/toolkit/Underscore/Underscore.m +100 -0
  73. data/lib/appjam/generators/templates/blank/EiffelApplication/main.m.tt +18 -0
  74. data/lib/appjam/generators/templates/blank/EiffelApplicationTests/EiffelApplicationTests-Info.plist +22 -0
  75. data/lib/appjam/generators/templates/blank/EiffelApplicationTests/EiffelApplicationTests.h.tt +13 -0
  76. data/lib/appjam/generators/templates/blank/EiffelApplicationTests/EiffelApplicationTests.m.tt +32 -0
  77. data/lib/appjam/generators/templates/blank/EiffelApplicationTests/en.lproj/InfoPlist.strings +2 -0
  78. data/lib/appjam/generators/templates/resources/Default-568h@2x.png +0 -0
  79. data/lib/appjam/generators/templates/resources/Default.png +0 -0
  80. data/lib/appjam/generators/templates/resources/Default@2x.png +0 -0
  81. data/lib/appjam/generators/templates/resources/contents.tt +4 -0
  82. data/lib/appjam/version.rb +1 -1
  83. metadata +462 -326
  84. data/test/helper.rb +0 -132
  85. data/test/test_model_generator.rb +0 -28
  86. data/test/test_project_generator.rb +0 -38
@@ -0,0 +1,379 @@
1
+ // AFURLConnectionOperation.h
2
+ //
3
+ // Copyright (c) 2011 Gowalla (http://gowalla.com/)
4
+ //
5
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ // of this software and associated documentation files (the "Software"), to deal
7
+ // in the Software without restriction, including without limitation the rights
8
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ // copies of the Software, and to permit persons to whom the Software is
10
+ // furnished to do so, subject to the following conditions:
11
+ //
12
+ // The above copyright notice and this permission notice shall be included in
13
+ // all copies or substantial portions of the Software.
14
+ //
15
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ // THE SOFTWARE.
22
+
23
+ #import <Foundation/Foundation.h>
24
+
25
+ #import <Availability.h>
26
+
27
+ /**
28
+ `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
29
+
30
+ ## Subclassing Notes
31
+
32
+ This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
33
+
34
+ If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
35
+
36
+ ## NSURLConnection Delegate Methods
37
+
38
+ `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
39
+
40
+ - `connection:didReceiveResponse:`
41
+ - `connection:didReceiveData:`
42
+ - `connectionDidFinishLoading:`
43
+ - `connection:didFailWithError:`
44
+ - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
45
+ - `connection:willCacheResponse:`
46
+ - `connection:canAuthenticateAgainstProtectionSpace:`
47
+ - `connection:didReceiveAuthenticationChallenge:`
48
+ - `connectionShouldUseCredentialStorage:`
49
+ - `connection:needNewBodyStream:`
50
+
51
+ If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
52
+
53
+ ## Class Constructors
54
+
55
+ Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
56
+
57
+ ## Callbacks and Completion Blocks
58
+
59
+ The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
60
+
61
+ Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
62
+
63
+ ## SSL Pinning
64
+
65
+ Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle.
66
+
67
+ SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
68
+
69
+ When `_AFNETWORKING_PIN_SSL_CERTIFICATES_` is defined and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
70
+
71
+ ## NSCoding & NSCopying Conformance
72
+
73
+ `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
74
+
75
+ ### NSCoding Caveats
76
+
77
+ - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
78
+ - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
79
+
80
+ ### NSCopying Caveats
81
+
82
+ - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
83
+ - A copy of an operation will not include the `outputStream` of the original.
84
+ - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
85
+ */
86
+
87
+ #ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
88
+ typedef enum {
89
+ AFSSLPinningModeNone,
90
+ AFSSLPinningModePublicKey,
91
+ AFSSLPinningModeCertificate,
92
+ } AFURLConnectionOperationSSLPinningMode;
93
+ #endif
94
+
95
+ @interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate,
96
+ #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_5_0) || \
97
+ (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_8)
98
+ NSURLConnectionDataDelegate,
99
+ #endif
100
+ NSCoding, NSCopying>
101
+
102
+ ///-------------------------------
103
+ /// @name Accessing Run Loop Modes
104
+ ///-------------------------------
105
+
106
+ /**
107
+ The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
108
+ */
109
+ @property (nonatomic, strong) NSSet *runLoopModes;
110
+
111
+ ///-----------------------------------------
112
+ /// @name Getting URL Connection Information
113
+ ///-----------------------------------------
114
+
115
+ /**
116
+ The request used by the operation's connection.
117
+ */
118
+ @property (readonly, nonatomic, strong) NSURLRequest *request;
119
+
120
+ /**
121
+ The last response received by the operation's connection.
122
+ */
123
+ @property (readonly, nonatomic, strong) NSURLResponse *response;
124
+
125
+ /**
126
+ The error, if any, that occurred in the lifecycle of the request.
127
+ */
128
+ @property (readonly, nonatomic, strong) NSError *error;
129
+
130
+ ///----------------------------
131
+ /// @name Getting Response Data
132
+ ///----------------------------
133
+
134
+ /**
135
+ The data received during the request.
136
+ */
137
+ @property (readonly, nonatomic, strong) NSData *responseData;
138
+
139
+ /**
140
+ The string representation of the response data.
141
+ */
142
+ @property (readonly, nonatomic, copy) NSString *responseString;
143
+
144
+ /**
145
+ The string encoding of the response.
146
+
147
+ @discussion If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
148
+ */
149
+ @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
150
+
151
+ ///-------------------------------
152
+ /// @name Managing URL Credentials
153
+ ///-------------------------------
154
+
155
+ /**
156
+ Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
157
+
158
+ @discussion This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
159
+ */
160
+ @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
161
+
162
+ /**
163
+ The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
164
+
165
+ @discussion This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
166
+ */
167
+ @property (nonatomic, strong) NSURLCredential *credential;
168
+
169
+ /**
170
+ The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default.
171
+
172
+ @discussion To enable SSL Pinning, `#define _AFNETWORKING_PIN_SSL_CERTIFICATES_` in `Prefix.pch`. Also, make sure that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information.
173
+ */
174
+ #ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
175
+ @property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode;
176
+ #endif
177
+
178
+ ///------------------------
179
+ /// @name Accessing Streams
180
+ ///------------------------
181
+
182
+ /**
183
+ The input stream used to read data to be sent during the request.
184
+
185
+ @discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`.
186
+ */
187
+ @property (nonatomic, strong) NSInputStream *inputStream;
188
+
189
+ /**
190
+ The output stream that is used to write data received until the request is finished.
191
+
192
+ @discussion By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
193
+ */
194
+ @property (nonatomic, strong) NSOutputStream *outputStream;
195
+
196
+ ///---------------------------------------------
197
+ /// @name Managing Request Operation Information
198
+ ///---------------------------------------------
199
+
200
+ /**
201
+ The user info dictionary for the receiver.
202
+ */
203
+ @property (nonatomic, strong) NSDictionary *userInfo;
204
+
205
+ ///------------------------------------------------------
206
+ /// @name Initializing an AFURLConnectionOperation Object
207
+ ///------------------------------------------------------
208
+
209
+ /**
210
+ Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
211
+
212
+ @param urlRequest The request object to be used by the operation connection.
213
+
214
+ @discussion This is the designated initializer.
215
+ */
216
+ - (id)initWithRequest:(NSURLRequest *)urlRequest;
217
+
218
+ ///----------------------------------
219
+ /// @name Pausing / Resuming Requests
220
+ ///----------------------------------
221
+
222
+ /**
223
+ Pauses the execution of the request operation.
224
+
225
+ @discussion A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
226
+ */
227
+ - (void)pause;
228
+
229
+ /**
230
+ Whether the request operation is currently paused.
231
+
232
+ @return `YES` if the operation is currently paused, otherwise `NO`.
233
+ */
234
+ - (BOOL)isPaused;
235
+
236
+ /**
237
+ Resumes the execution of the paused request operation.
238
+
239
+ @discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
240
+ */
241
+ - (void)resume;
242
+
243
+ ///----------------------------------------------
244
+ /// @name Configuring Backgrounding Task Behavior
245
+ ///----------------------------------------------
246
+
247
+ /**
248
+ Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
249
+
250
+ @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
251
+ */
252
+ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
253
+ - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
254
+ #endif
255
+
256
+ ///---------------------------------
257
+ /// @name Setting Progress Callbacks
258
+ ///---------------------------------
259
+
260
+ /**
261
+ Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
262
+
263
+ @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
264
+ */
265
+ - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
266
+
267
+ /**
268
+ Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
269
+
270
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
271
+ */
272
+ - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
273
+
274
+ ///-------------------------------------------------
275
+ /// @name Setting NSURLConnection Delegate Callbacks
276
+ ///-------------------------------------------------
277
+
278
+ /**
279
+ Sets a block to be executed to determine whether the connection should be able to respond to a protection space's form of authentication, as handled by the `NSURLConnectionDelegate` method `connection:canAuthenticateAgainstProtectionSpace:`.
280
+
281
+ @param block A block object to be executed to determine whether the connection should be able to respond to a protection space's form of authentication. The block has a `BOOL` return type and takes two arguments: the URL connection object, and the protection space to authenticate against.
282
+
283
+ @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:canAuthenticateAgainstProtectionSpace:` will accept invalid SSL certificates, returning `YES` if the protection space authentication method is `NSURLAuthenticationMethodServerTrust`.
284
+ */
285
+ - (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block;
286
+
287
+ /**
288
+ Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:didReceiveAuthenticationChallenge:`.
289
+
290
+ @param block A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated.
291
+
292
+ @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:didReceiveAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
293
+ */
294
+ - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
295
+
296
+ /**
297
+ Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
298
+
299
+ @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
300
+ */
301
+ - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
302
+
303
+
304
+ /**
305
+ Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
306
+
307
+ @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
308
+ */
309
+ - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
310
+
311
+ @end
312
+
313
+ ///----------------
314
+ /// @name Constants
315
+ ///----------------
316
+
317
+ /**
318
+ ## SSL Pinning Options
319
+
320
+ The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options.
321
+
322
+ enum {
323
+ AFSSLPinningModeNone,
324
+ AFSSLPinningModePublicKey,
325
+ AFSSLPinningModeCertificate,
326
+ }
327
+
328
+ `AFSSLPinningModeNone`
329
+ Do not pin SSL connections
330
+
331
+ `AFSSLPinningModePublicKey`
332
+ Pin SSL connections to certificate public key (SPKI).
333
+
334
+ `AFSSLPinningModeCertificate`
335
+ Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance.
336
+
337
+ ## User info dictionary keys
338
+
339
+ These keys may exist in the user info dictionary, in addition to those defined for NSError.
340
+
341
+ - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
342
+ - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
343
+
344
+ ### Constants
345
+
346
+ `AFNetworkingOperationFailingURLRequestErrorKey`
347
+ The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
348
+
349
+ `AFNetworkingOperationFailingURLResponseErrorKey`
350
+ The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
351
+
352
+ ## Error Domains
353
+
354
+ The following error domain is predefined.
355
+
356
+ - `NSString * const AFNetworkingErrorDomain`
357
+
358
+ ### Constants
359
+
360
+ `AFNetworkingErrorDomain`
361
+ AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
362
+ */
363
+ extern NSString * const AFNetworkingErrorDomain;
364
+ extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
365
+ extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
366
+
367
+ ///--------------------
368
+ /// @name Notifications
369
+ ///--------------------
370
+
371
+ /**
372
+ Posted when an operation begins executing.
373
+ */
374
+ extern NSString * const AFNetworkingOperationDidStartNotification;
375
+
376
+ /**
377
+ Posted when an operation finishes.
378
+ */
379
+ extern NSString * const AFNetworkingOperationDidFinishNotification;
@@ -0,0 +1,818 @@
1
+ // AFURLConnectionOperation.m
2
+ //
3
+ // Copyright (c) 2011 Gowalla (http://gowalla.com/)
4
+ //
5
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ // of this software and associated documentation files (the "Software"), to deal
7
+ // in the Software without restriction, including without limitation the rights
8
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ // copies of the Software, and to permit persons to whom the Software is
10
+ // furnished to do so, subject to the following conditions:
11
+ //
12
+ // The above copyright notice and this permission notice shall be included in
13
+ // all copies or substantial portions of the Software.
14
+ //
15
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ // THE SOFTWARE.
22
+
23
+ #import "AFURLConnectionOperation.h"
24
+
25
+ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
26
+ #import <UIKit/UIKit.h>
27
+ #endif
28
+
29
+ #if !__has_feature(objc_arc)
30
+ #error AFNetworking must be built with ARC.
31
+ // You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
32
+ #endif
33
+
34
+ typedef enum {
35
+ AFOperationPausedState = -1,
36
+ AFOperationReadyState = 1,
37
+ AFOperationExecutingState = 2,
38
+ AFOperationFinishedState = 3,
39
+ } _AFOperationState;
40
+
41
+ typedef signed short AFOperationState;
42
+
43
+ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
44
+ typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier;
45
+ #else
46
+ typedef id AFBackgroundTaskIdentifier;
47
+ #endif
48
+
49
+ static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
50
+
51
+ NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain";
52
+ NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey";
53
+ NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey";
54
+
55
+ NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
56
+ NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
57
+
58
+ typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
59
+ typedef BOOL (^AFURLConnectionOperationAuthenticationAgainstProtectionSpaceBlock)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace);
60
+ typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
61
+ typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
62
+ typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
63
+
64
+ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
65
+ switch (state) {
66
+ case AFOperationReadyState:
67
+ return @"isReady";
68
+ case AFOperationExecutingState:
69
+ return @"isExecuting";
70
+ case AFOperationFinishedState:
71
+ return @"isFinished";
72
+ case AFOperationPausedState:
73
+ return @"isPaused";
74
+ default:
75
+ return @"state";
76
+ }
77
+ }
78
+
79
+ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) {
80
+ switch (fromState) {
81
+ case AFOperationReadyState:
82
+ switch (toState) {
83
+ case AFOperationPausedState:
84
+ case AFOperationExecutingState:
85
+ return YES;
86
+ case AFOperationFinishedState:
87
+ return isCancelled;
88
+ default:
89
+ return NO;
90
+ }
91
+ case AFOperationExecutingState:
92
+ switch (toState) {
93
+ case AFOperationPausedState:
94
+ case AFOperationFinishedState:
95
+ return YES;
96
+ default:
97
+ return NO;
98
+ }
99
+ case AFOperationFinishedState:
100
+ return NO;
101
+ case AFOperationPausedState:
102
+ return toState == AFOperationReadyState;
103
+ default:
104
+ return YES;
105
+ }
106
+ }
107
+
108
+ @interface AFURLConnectionOperation ()
109
+ @property (readwrite, nonatomic, assign) AFOperationState state;
110
+ @property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
111
+ @property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
112
+ @property (readwrite, nonatomic, strong) NSURLConnection *connection;
113
+ @property (readwrite, nonatomic, strong) NSURLRequest *request;
114
+ @property (readwrite, nonatomic, strong) NSURLResponse *response;
115
+ @property (readwrite, nonatomic, strong) NSError *error;
116
+ @property (readwrite, nonatomic, strong) NSData *responseData;
117
+ @property (readwrite, nonatomic, copy) NSString *responseString;
118
+ @property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
119
+ @property (readwrite, nonatomic, assign) long long totalBytesRead;
120
+ @property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier;
121
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
122
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
123
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationAgainstProtectionSpaceBlock authenticationAgainstProtectionSpace;
124
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
125
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse;
126
+ @property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse;
127
+
128
+ - (void)operationDidStart;
129
+ - (void)finish;
130
+ - (void)cancelConnection;
131
+ @end
132
+
133
+ @implementation AFURLConnectionOperation
134
+ @synthesize state = _state;
135
+ @synthesize cancelled = _cancelled;
136
+ @synthesize connection = _connection;
137
+ @synthesize runLoopModes = _runLoopModes;
138
+ @synthesize request = _request;
139
+ @synthesize response = _response;
140
+ @synthesize error = _error;
141
+ @synthesize responseData = _responseData;
142
+ @synthesize responseString = _responseString;
143
+ @synthesize responseStringEncoding = _responseStringEncoding;
144
+ @synthesize totalBytesRead = _totalBytesRead;
145
+ @dynamic inputStream;
146
+ @synthesize outputStream = _outputStream;
147
+ @synthesize credential = _credential;
148
+ #ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
149
+ @synthesize SSLPinningMode = _SSLPinningMode;
150
+ #endif
151
+ @synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage;
152
+ @synthesize userInfo = _userInfo;
153
+ @synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier;
154
+ @synthesize uploadProgress = _uploadProgress;
155
+ @synthesize downloadProgress = _downloadProgress;
156
+ @synthesize authenticationAgainstProtectionSpace = _authenticationAgainstProtectionSpace;
157
+ @synthesize authenticationChallenge = _authenticationChallenge;
158
+ @synthesize cacheResponse = _cacheResponse;
159
+ @synthesize redirectResponse = _redirectResponse;
160
+ @synthesize lock = _lock;
161
+
162
+ + (void) __attribute__((noreturn)) networkRequestThreadEntryPoint:(id)__unused object {
163
+ do {
164
+ @autoreleasepool {
165
+ [[NSRunLoop currentRunLoop] run];
166
+ }
167
+ } while (YES);
168
+ }
169
+
170
+ + (NSThread *)networkRequestThread {
171
+ static NSThread *_networkRequestThread = nil;
172
+ static dispatch_once_t oncePredicate;
173
+ dispatch_once(&oncePredicate, ^{
174
+ _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
175
+ [_networkRequestThread start];
176
+ });
177
+
178
+ return _networkRequestThread;
179
+ }
180
+
181
+ #ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
182
+ + (NSArray *)pinnedCertificates {
183
+ static NSArray *_pinnedCertificates = nil;
184
+ static dispatch_once_t onceToken;
185
+ dispatch_once(&onceToken, ^{
186
+ NSBundle *bundle = [NSBundle bundleForClass:[self class]];
187
+ NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
188
+
189
+ NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
190
+ for (NSString *path in paths) {
191
+ NSData *certificateData = [NSData dataWithContentsOfFile:path];
192
+ [certificates addObject:certificateData];
193
+ }
194
+
195
+ _pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
196
+ });
197
+
198
+ return _pinnedCertificates;
199
+ }
200
+
201
+ + (NSArray *)pinnedPublicKeys {
202
+ static NSArray *_pinnedPublicKeys = nil;
203
+ static dispatch_once_t onceToken;
204
+ dispatch_once(&onceToken, ^{
205
+ NSArray *pinnedCertificates = [self pinnedCertificates];
206
+ NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]];
207
+
208
+ for (NSData *data in pinnedCertificates) {
209
+ SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
210
+ NSCParameterAssert(allowedCertificate);
211
+
212
+ SecCertificateRef allowedCertificates[] = {allowedCertificate};
213
+ CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
214
+
215
+ SecPolicyRef policy = SecPolicyCreateBasicX509();
216
+ SecTrustRef allowedTrust = NULL;
217
+ OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust);
218
+ NSAssert(status == noErr, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
219
+
220
+ SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
221
+ [publicKeys addObject:(__bridge_transfer id)allowedPublicKey];
222
+
223
+ CFRelease(allowedTrust);
224
+ CFRelease(policy);
225
+ CFRelease(certificates);
226
+ CFRelease(allowedCertificate);
227
+ }
228
+
229
+ _pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys];
230
+ });
231
+
232
+ return _pinnedPublicKeys;
233
+ }
234
+ #endif
235
+
236
+ - (id)initWithRequest:(NSURLRequest *)urlRequest {
237
+ self = [super init];
238
+ if (!self) {
239
+ return nil;
240
+ }
241
+
242
+ self.lock = [[NSRecursiveLock alloc] init];
243
+ self.lock.name = kAFNetworkingLockName;
244
+
245
+ self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
246
+
247
+ self.request = urlRequest;
248
+
249
+ self.shouldUseCredentialStorage = YES;
250
+
251
+ self.outputStream = [NSOutputStream outputStreamToMemory];
252
+
253
+ self.state = AFOperationReadyState;
254
+
255
+ return self;
256
+ }
257
+
258
+ - (void)dealloc {
259
+ if (_outputStream) {
260
+ [_outputStream close];
261
+ _outputStream = nil;
262
+ }
263
+
264
+ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
265
+ if (_backgroundTaskIdentifier) {
266
+ [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
267
+ _backgroundTaskIdentifier = UIBackgroundTaskInvalid;
268
+ }
269
+ #endif
270
+ }
271
+
272
+ - (NSString *)description {
273
+ return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
274
+ }
275
+
276
+ - (void)setCompletionBlock:(void (^)(void))block {
277
+ [self.lock lock];
278
+ if (!block) {
279
+ [super setCompletionBlock:nil];
280
+ } else {
281
+ __weak __typeof(&*self)weakSelf = self;
282
+ [super setCompletionBlock:^ {
283
+ __strong __typeof(&*weakSelf)strongSelf = weakSelf;
284
+
285
+ block();
286
+ [strongSelf setCompletionBlock:nil];
287
+ }];
288
+ }
289
+ [self.lock unlock];
290
+ }
291
+
292
+ - (NSInputStream *)inputStream {
293
+ return self.request.HTTPBodyStream;
294
+ }
295
+
296
+ - (void)setInputStream:(NSInputStream *)inputStream {
297
+ [self willChangeValueForKey:@"inputStream"];
298
+ NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
299
+ mutableRequest.HTTPBodyStream = inputStream;
300
+ self.request = mutableRequest;
301
+ [self didChangeValueForKey:@"inputStream"];
302
+ }
303
+
304
+ - (void)setOutputStream:(NSOutputStream *)outputStream {
305
+ if (outputStream == _outputStream) {
306
+ return;
307
+ }
308
+
309
+ [self willChangeValueForKey:@"outputStream"];
310
+ if (_outputStream) {
311
+ [_outputStream close];
312
+ }
313
+ _outputStream = outputStream;
314
+ [self didChangeValueForKey:@"outputStream"];
315
+ }
316
+
317
+ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
318
+ - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
319
+ [self.lock lock];
320
+ if (!self.backgroundTaskIdentifier) {
321
+ UIApplication *application = [UIApplication sharedApplication];
322
+ __weak __typeof(&*self)weakSelf = self;
323
+ self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
324
+ __strong __typeof(&*weakSelf)strongSelf = weakSelf;
325
+
326
+ if (handler) {
327
+ handler();
328
+ }
329
+
330
+ if (strongSelf) {
331
+ [strongSelf cancel];
332
+
333
+ [application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
334
+ strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
335
+ }
336
+ }];
337
+ }
338
+ [self.lock unlock];
339
+ }
340
+ #endif
341
+
342
+ - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
343
+ self.uploadProgress = block;
344
+ }
345
+
346
+ - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
347
+ self.downloadProgress = block;
348
+ }
349
+
350
+ - (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *, NSURLProtectionSpace *))block {
351
+ self.authenticationAgainstProtectionSpace = block;
352
+ }
353
+
354
+ - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
355
+ self.authenticationChallenge = block;
356
+ }
357
+
358
+ - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
359
+ self.cacheResponse = block;
360
+ }
361
+
362
+ - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
363
+ self.redirectResponse = block;
364
+ }
365
+
366
+ - (void)setState:(AFOperationState)state {
367
+ if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
368
+ return;
369
+ }
370
+
371
+ [self.lock lock];
372
+ NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
373
+ NSString *newStateKey = AFKeyPathFromOperationState(state);
374
+
375
+ [self willChangeValueForKey:newStateKey];
376
+ [self willChangeValueForKey:oldStateKey];
377
+ _state = state;
378
+ [self didChangeValueForKey:oldStateKey];
379
+ [self didChangeValueForKey:newStateKey];
380
+ [self.lock unlock];
381
+ }
382
+
383
+ - (NSString *)responseString {
384
+ [self.lock lock];
385
+ if (!_responseString && self.response && self.responseData) {
386
+ self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
387
+ }
388
+ [self.lock unlock];
389
+
390
+ return _responseString;
391
+ }
392
+
393
+ - (NSStringEncoding)responseStringEncoding {
394
+ [self.lock lock];
395
+ if (!_responseStringEncoding && self.response) {
396
+ NSStringEncoding stringEncoding = NSUTF8StringEncoding;
397
+ if (self.response.textEncodingName) {
398
+ CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
399
+ if (IANAEncoding != kCFStringEncodingInvalidId) {
400
+ stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
401
+ }
402
+ }
403
+
404
+ self.responseStringEncoding = stringEncoding;
405
+ }
406
+ [self.lock unlock];
407
+
408
+ return _responseStringEncoding;
409
+ }
410
+
411
+ - (void)pause {
412
+ if ([self isPaused] || [self isFinished] || [self isCancelled]) {
413
+ return;
414
+ }
415
+
416
+ [self.lock lock];
417
+
418
+ if ([self isExecuting]) {
419
+ [self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
420
+
421
+ dispatch_async(dispatch_get_main_queue(), ^{
422
+ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
423
+ [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
424
+ });
425
+ }
426
+
427
+ self.state = AFOperationPausedState;
428
+
429
+ [self.lock unlock];
430
+ }
431
+
432
+ - (BOOL)isPaused {
433
+ return self.state == AFOperationPausedState;
434
+ }
435
+
436
+ - (void)resume {
437
+ if (![self isPaused]) {
438
+ return;
439
+ }
440
+
441
+ [self.lock lock];
442
+ self.state = AFOperationReadyState;
443
+
444
+ [self start];
445
+ [self.lock unlock];
446
+ }
447
+
448
+ #pragma mark - NSOperation
449
+
450
+ - (BOOL)isReady {
451
+ return self.state == AFOperationReadyState && [super isReady];
452
+ }
453
+
454
+ - (BOOL)isExecuting {
455
+ return self.state == AFOperationExecutingState;
456
+ }
457
+
458
+ - (BOOL)isFinished {
459
+ return self.state == AFOperationFinishedState;
460
+ }
461
+
462
+ - (BOOL)isConcurrent {
463
+ return YES;
464
+ }
465
+
466
+ - (void)start {
467
+ [self.lock lock];
468
+ if ([self isReady]) {
469
+ self.state = AFOperationExecutingState;
470
+
471
+ [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
472
+ }
473
+ [self.lock unlock];
474
+ }
475
+
476
+ - (void)operationDidStart {
477
+ [self.lock lock];
478
+ if (! [self isCancelled]) {
479
+ self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
480
+
481
+ NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
482
+ for (NSString *runLoopMode in self.runLoopModes) {
483
+ [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
484
+ [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
485
+ }
486
+
487
+ [self.connection start];
488
+ }
489
+ [self.lock unlock];
490
+
491
+ dispatch_async(dispatch_get_main_queue(), ^{
492
+ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
493
+ });
494
+
495
+ if ([self isCancelled]) {
496
+ [self finish];
497
+ }
498
+ }
499
+
500
+ - (void)finish {
501
+ self.state = AFOperationFinishedState;
502
+
503
+ dispatch_async(dispatch_get_main_queue(), ^{
504
+ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
505
+ });
506
+ }
507
+
508
+ - (void)cancel {
509
+ [self.lock lock];
510
+ if (![self isFinished] && ![self isCancelled]) {
511
+ [self willChangeValueForKey:@"isCancelled"];
512
+ _cancelled = YES;
513
+ [super cancel];
514
+ [self didChangeValueForKey:@"isCancelled"];
515
+
516
+ // Cancel the connection on the thread it runs on to prevent race conditions
517
+ [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
518
+ }
519
+ [self.lock unlock];
520
+ }
521
+
522
+ - (void)cancelConnection {
523
+ NSDictionary *userInfo = nil;
524
+ if ([self.request URL]) {
525
+ userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
526
+ }
527
+ self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
528
+
529
+ if (self.connection) {
530
+ [self.connection cancel];
531
+
532
+ // Manually send this delegate message since `[self.connection cancel]` causes the connection to never send another message to its delegate
533
+ [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.error];
534
+ }
535
+ }
536
+
537
+ #pragma mark - NSURLConnectionDelegate
538
+
539
+ #ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
540
+ - (void)connection:(NSURLConnection *)connection
541
+ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
542
+ {
543
+ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
544
+ SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
545
+ SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
546
+ NSData *certificateData = (__bridge_transfer NSData *)SecCertificateCopyData(certificate);
547
+
548
+ if ([[[self class] pinnedCertificates] containsObject:certificateData]) {
549
+ NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
550
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
551
+ } else {
552
+ switch (self.SSLPinningMode) {
553
+ case AFSSLPinningModePublicKey: {
554
+ id publicKey = (__bridge_transfer id)SecTrustCopyPublicKey(serverTrust);
555
+
556
+ if ([[self.class pinnedPublicKeys] containsObject:publicKey]) {
557
+ NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
558
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
559
+ } else {
560
+ [[challenge sender] cancelAuthenticationChallenge:challenge];
561
+ }
562
+
563
+ break;
564
+ }
565
+ case AFSSLPinningModeCertificate: {
566
+ SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
567
+ NSData *serverCertificateData = (__bridge_transfer NSData *)SecCertificateCopyData(serverCertificate);
568
+
569
+ if ([[[self class] pinnedCertificates] containsObject:serverCertificateData]) {
570
+ NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
571
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
572
+ } else {
573
+ [[challenge sender] cancelAuthenticationChallenge:challenge];
574
+ }
575
+
576
+ break;
577
+ }
578
+ case AFSSLPinningModeNone: {
579
+ #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
580
+ NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
581
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
582
+ #else
583
+ SecTrustResultType result = 0;
584
+ OSStatus status = SecTrustEvaluate(serverTrust, &result);
585
+ NSAssert(status == noErr, @"SecTrustEvaluate error: %ld", (long int)status);
586
+
587
+ if (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed) {
588
+ NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
589
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
590
+ } else {
591
+ [[challenge sender] cancelAuthenticationChallenge:challenge];
592
+ }
593
+ #endif
594
+ break;
595
+ }
596
+ }
597
+ }
598
+ }
599
+ }
600
+ #endif
601
+
602
+
603
+ - (BOOL)connection:(NSURLConnection *)connection
604
+ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
605
+ {
606
+ #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
607
+ if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
608
+ return YES;
609
+ }
610
+ #endif
611
+
612
+ if (self.authenticationAgainstProtectionSpace) {
613
+ return self.authenticationAgainstProtectionSpace(connection, protectionSpace);
614
+ } else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
615
+ return NO;
616
+ } else {
617
+ return YES;
618
+ }
619
+ }
620
+
621
+ - (void)connection:(NSURLConnection *)connection
622
+ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
623
+ {
624
+ #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
625
+ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
626
+ [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
627
+ return;
628
+ }
629
+ #endif
630
+
631
+ if (self.authenticationChallenge) {
632
+ self.authenticationChallenge(connection, challenge);
633
+ } else {
634
+ if ([challenge previousFailureCount] == 0) {
635
+ NSURLCredential *credential = nil;
636
+
637
+ NSString *user = [[self.request URL] user];
638
+ NSString *password = [[self.request URL] password];
639
+
640
+ if (user && password) {
641
+ credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceNone];
642
+ } else if (user) {
643
+ credential = [[[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:[challenge protectionSpace]] objectForKey:user];
644
+ } else {
645
+ credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[challenge protectionSpace]];
646
+ }
647
+
648
+ if (!credential) {
649
+ credential = self.credential;
650
+ }
651
+
652
+ if (credential) {
653
+ [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
654
+ } else {
655
+ [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
656
+ }
657
+ } else {
658
+ [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
659
+ }
660
+ }
661
+ }
662
+
663
+ - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
664
+ return self.shouldUseCredentialStorage;
665
+ }
666
+
667
+ - (NSInputStream *)connection:(NSURLConnection __unused *)connection
668
+ needNewBodyStream:(NSURLRequest *)request
669
+ {
670
+ if ([request.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
671
+ return [request.HTTPBodyStream copy];
672
+ }
673
+
674
+ return nil;
675
+ }
676
+
677
+ - (NSURLRequest *)connection:(NSURLConnection *)connection
678
+ willSendRequest:(NSURLRequest *)request
679
+ redirectResponse:(NSURLResponse *)redirectResponse
680
+ {
681
+ if (self.redirectResponse) {
682
+ return self.redirectResponse(connection, request, redirectResponse);
683
+ } else {
684
+ return request;
685
+ }
686
+ }
687
+
688
+ - (void)connection:(NSURLConnection __unused *)connection
689
+ didSendBodyData:(NSInteger)bytesWritten
690
+ totalBytesWritten:(NSInteger)totalBytesWritten
691
+ totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
692
+ {
693
+ if (self.uploadProgress) {
694
+ dispatch_async(dispatch_get_main_queue(), ^{
695
+ self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
696
+ });
697
+ }
698
+ }
699
+
700
+ - (void)connection:(NSURLConnection __unused *)connection
701
+ didReceiveResponse:(NSURLResponse *)response
702
+ {
703
+ self.response = response;
704
+
705
+ [self.outputStream open];
706
+ }
707
+
708
+ - (void)connection:(NSURLConnection __unused *)connection
709
+ didReceiveData:(NSData *)data
710
+ {
711
+ if ([self.outputStream hasSpaceAvailable]) {
712
+ const uint8_t *dataBuffer = (uint8_t *) [data bytes];
713
+ [self.outputStream write:&dataBuffer[0] maxLength:[data length]];
714
+ }
715
+
716
+ dispatch_async(dispatch_get_main_queue(), ^{
717
+ self.totalBytesRead += [data length];
718
+
719
+ if (self.downloadProgress) {
720
+ self.downloadProgress([data length], self.totalBytesRead, self.response.expectedContentLength);
721
+ }
722
+ });
723
+ }
724
+
725
+ - (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
726
+ self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
727
+
728
+ [self.outputStream close];
729
+
730
+ [self finish];
731
+
732
+ self.connection = nil;
733
+ }
734
+
735
+ - (void)connection:(NSURLConnection __unused *)connection
736
+ didFailWithError:(NSError *)error
737
+ {
738
+ self.error = error;
739
+
740
+ [self.outputStream close];
741
+
742
+ [self finish];
743
+
744
+ self.connection = nil;
745
+ }
746
+
747
+ - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
748
+ willCacheResponse:(NSCachedURLResponse *)cachedResponse
749
+ {
750
+ if (self.cacheResponse) {
751
+ return self.cacheResponse(connection, cachedResponse);
752
+ } else {
753
+ if ([self isCancelled]) {
754
+ return nil;
755
+ }
756
+
757
+ return cachedResponse;
758
+ }
759
+ }
760
+
761
+ #pragma mark - NSCoding
762
+
763
+ - (id)initWithCoder:(NSCoder *)aDecoder {
764
+ NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
765
+
766
+ self = [self initWithRequest:request];
767
+ if (!self) {
768
+ return nil;
769
+ }
770
+
771
+ self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"];
772
+ self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"];
773
+ self.response = [aDecoder decodeObjectForKey:@"response"];
774
+ self.error = [aDecoder decodeObjectForKey:@"error"];
775
+ self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
776
+ self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
777
+
778
+ return self;
779
+ }
780
+
781
+ - (void)encodeWithCoder:(NSCoder *)aCoder {
782
+ [self pause];
783
+
784
+ [aCoder encodeObject:self.request forKey:@"request"];
785
+
786
+ switch (self.state) {
787
+ case AFOperationExecutingState:
788
+ case AFOperationPausedState:
789
+ [aCoder encodeInteger:AFOperationReadyState forKey:@"state"];
790
+ break;
791
+ default:
792
+ [aCoder encodeInteger:self.state forKey:@"state"];
793
+ break;
794
+ }
795
+
796
+ [aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
797
+ [aCoder encodeObject:self.response forKey:@"response"];
798
+ [aCoder encodeObject:self.error forKey:@"error"];
799
+ [aCoder encodeObject:self.responseData forKey:@"responseData"];
800
+ [aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"];
801
+ }
802
+
803
+ #pragma mark - NSCopying
804
+
805
+ - (id)copyWithZone:(NSZone *)zone {
806
+ AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
807
+
808
+ operation.uploadProgress = self.uploadProgress;
809
+ operation.downloadProgress = self.downloadProgress;
810
+ operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace;
811
+ operation.authenticationChallenge = self.authenticationChallenge;
812
+ operation.cacheResponse = self.cacheResponse;
813
+ operation.redirectResponse = self.redirectResponse;
814
+
815
+ return operation;
816
+ }
817
+
818
+ @end