MKNetworkOperation.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  1. //
  2. // MKNetworkOperation.m
  3. // MKNetworkKit
  4. //
  5. // Created by Mugunth Kumar (@mugunthkumar) on 11/11/11.
  6. // Copyright (C) 2011-2020 by Steinlogic Consulting and Training Pte Ltd
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. #import "MKNetworkKit.h"
  25. #ifdef __OBJC_GC__
  26. #error MKNetworkKit does not support Objective-C Garbage Collection
  27. #endif
  28. #if TARGET_OS_IPHONE
  29. #ifndef __IPHONE_5_0
  30. #error MKNetworkKit does not support iOS 4 and lower
  31. #endif
  32. #endif
  33. #if ! __has_feature(objc_arc)
  34. #error MKNetworkKit is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
  35. #endif
  36. OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data,
  37. SecIdentityRef *outIdentity,
  38. SecTrustRef *outTrust,
  39. CFStringRef keyPassword);
  40. @interface MKNetworkOperation (/*Private Methods*/)
  41. @property (strong, nonatomic) NSURLConnection *connection;
  42. @property (copy, nonatomic) NSString *uniqueId;
  43. @property (strong, nonatomic) NSMutableURLRequest *request;
  44. @property (strong, nonatomic) NSHTTPURLResponse *response;
  45. @property (strong, nonatomic) NSMutableDictionary *fieldsToBePosted;
  46. @property (strong, nonatomic) NSMutableArray *filesToBePosted;
  47. @property (strong, nonatomic) NSMutableArray *dataToBePosted;
  48. @property (copy, nonatomic) NSString *username;
  49. @property (copy, nonatomic) NSString *password;
  50. @property (nonatomic, strong) NSMutableArray *responseBlocks;
  51. @property (nonatomic, strong) NSMutableArray *errorBlocks;
  52. @property (nonatomic, strong) NSMutableArray *errorBlocksType2;
  53. @property (nonatomic, assign) MKNetworkOperationState state;
  54. @property (nonatomic, assign) BOOL isCancelled;
  55. @property (strong, nonatomic) NSMutableData *mutableData;
  56. @property (assign, nonatomic) NSUInteger downloadedDataSize;
  57. @property (nonatomic, strong) NSMutableArray *notModifiedHandlers;
  58. @property (nonatomic, strong) NSMutableArray *uploadProgressChangedHandlers;
  59. @property (nonatomic, strong) NSMutableArray *downloadProgressChangedHandlers;
  60. @property (nonatomic, copy) MKNKEncodingBlock postDataEncodingHandler;
  61. @property (nonatomic, assign) NSInteger startPosition;
  62. @property (nonatomic, strong) NSMutableArray *downloadStreams;
  63. @property (nonatomic, copy) NSData *cachedResponse;
  64. @property (nonatomic, copy) MKNKResponseBlock cacheHandlingBlock;
  65. @property (nonatomic, assign) SecTrustRef serverTrust;
  66. #if TARGET_OS_IPHONE
  67. @property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskId;
  68. #endif
  69. @property (strong, nonatomic) NSError *error;
  70. - (id)initWithURLString:(NSString *)aURLString
  71. params:(NSDictionary *)body
  72. httpMethod:(NSString *)method;
  73. -(NSData*) bodyData;
  74. -(NSString*) encodedPostDataString;
  75. - (void) showLocalNotification;
  76. - (void) endBackgroundTask;
  77. @end
  78. @implementation MKNetworkOperation
  79. @dynamic freezable;
  80. // A RESTful service should always return the same response for a given URL and it's parameters.
  81. // this means if these values are correct, you can cache the responses
  82. // This is another reason why we check only GET methods.
  83. // even if URL and others are same, POST, DELETE, PUT methods should not be cached and should not be treated equal.
  84. -(BOOL) isCacheable {
  85. return [self.request.HTTPMethod isEqualToString:@"GET"];
  86. }
  87. //===========================================================
  88. // + (BOOL)automaticallyNotifiesObserversForKey:
  89. //
  90. //===========================================================
  91. + (BOOL)automaticallyNotifiesObserversForKey: (NSString *)theKey
  92. {
  93. BOOL automatic;
  94. if ([theKey isEqualToString:@"postDataEncoding"]) {
  95. automatic = NO;
  96. } else {
  97. automatic = [super automaticallyNotifiesObserversForKey:theKey];
  98. }
  99. return automatic;
  100. }
  101. //===========================================================
  102. // postDataEncoding
  103. //===========================================================
  104. - (MKNKPostDataEncodingType)postDataEncoding
  105. {
  106. return _postDataEncoding;
  107. }
  108. - (void)setPostDataEncoding:(MKNKPostDataEncodingType)aPostDataEncoding
  109. {
  110. _postDataEncoding = aPostDataEncoding;
  111. NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
  112. switch (self.postDataEncoding) {
  113. case MKNKPostDataEncodingTypeURL: {
  114. [self.request setValue:
  115. [NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset]
  116. forHTTPHeaderField:@"Content-Type"];
  117. }
  118. break;
  119. case MKNKPostDataEncodingTypeJSON: {
  120. [self.request setValue:
  121. [NSString stringWithFormat:@"application/json; charset=%@", charset]
  122. forHTTPHeaderField:@"Content-Type"];
  123. }
  124. break;
  125. case MKNKPostDataEncodingTypePlist: {
  126. [self.request setValue:
  127. [NSString stringWithFormat:@"application/x-plist; charset=%@", charset]
  128. forHTTPHeaderField:@"Content-Type"];
  129. }
  130. default:
  131. break;
  132. }
  133. }
  134. -(NSString*) encodedPostDataString {
  135. NSString *returnValue = @"";
  136. if(self.postDataEncodingHandler)
  137. returnValue = self.postDataEncodingHandler(self.fieldsToBePosted);
  138. else if(self.postDataEncoding == MKNKPostDataEncodingTypeURL)
  139. returnValue = [self.fieldsToBePosted urlEncodedKeyValueString];
  140. else if(self.postDataEncoding == MKNKPostDataEncodingTypeJSON)
  141. returnValue = [self.fieldsToBePosted jsonEncodedKeyValueString];
  142. else if(self.postDataEncoding == MKNKPostDataEncodingTypePlist)
  143. returnValue = [self.fieldsToBePosted plistEncodedKeyValueString];
  144. return returnValue;
  145. }
  146. -(void) setCustomPostDataEncodingHandler:(MKNKEncodingBlock) postDataEncodingHandler forType:(NSString*) contentType {
  147. NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
  148. self.postDataEncoding = MKNKPostDataEncodingTypeCustom;
  149. self.postDataEncodingHandler = postDataEncodingHandler;
  150. [self.request setValue:
  151. [NSString stringWithFormat:@"%@; charset=%@", contentType, charset]
  152. forHTTPHeaderField:@"Content-Type"];
  153. }
  154. //===========================================================
  155. // freezable
  156. //===========================================================
  157. - (BOOL)freezable
  158. {
  159. return _freezable;
  160. }
  161. -(NSString*) url {
  162. return [[self.request URL] absoluteString];
  163. }
  164. -(NSURLRequest*) readonlyRequest {
  165. return [self.request copy];
  166. }
  167. -(NSHTTPURLResponse*) readonlyResponse {
  168. return [self.response copy];
  169. }
  170. - (NSDictionary *) readonlyPostDictionary {
  171. return [self.fieldsToBePosted copy];
  172. }
  173. -(NSString*) HTTPMethod {
  174. return self.request.HTTPMethod;
  175. }
  176. -(NSInteger) HTTPStatusCode {
  177. if(self.response)
  178. return self.response.statusCode;
  179. else
  180. return 0;
  181. }
  182. - (void)setFreezable:(BOOL)flag
  183. {
  184. // get method cannot be frozen.
  185. // No point in freezing a method that doesn't change server state.
  186. if([self.request.HTTPMethod isEqualToString:@"GET"] && flag) return;
  187. _freezable = flag;
  188. if(_freezable && self.uniqueId == nil)
  189. self.uniqueId = [NSString uniqueString];
  190. }
  191. -(BOOL) isEqual:(id)object {
  192. if([self.request.HTTPMethod isEqualToString:@"GET"] || [self.request.HTTPMethod isEqualToString:@"HEAD"]) {
  193. MKNetworkOperation *anotherObject = (MKNetworkOperation*) object;
  194. return ([[self uniqueIdentifier] isEqualToString:[anotherObject uniqueIdentifier]]);
  195. }
  196. return NO;
  197. }
  198. -(NSString*) uniqueIdentifier {
  199. NSMutableString *str = [NSMutableString stringWithFormat:@"%@ %@", self.request.HTTPMethod, self.url];
  200. if(self.username || self.password) {
  201. [str appendFormat:@" [%@:%@]",
  202. self.username ? self.username : @"",
  203. self.password ? self.password : @""];
  204. }
  205. if(self.freezable) {
  206. [str appendString:self.uniqueId];
  207. }
  208. return [str md5];
  209. }
  210. -(BOOL) isCachedResponse {
  211. return self.cachedResponse != nil;
  212. }
  213. -(void) notifyCache {
  214. if(![self isCacheable]) return;
  215. if(!([self.response statusCode] >= 200 && [self.response statusCode] < 300)) return;
  216. if(![self isCancelled])
  217. self.cacheHandlingBlock(self);
  218. }
  219. -(MKNetworkOperationState) state {
  220. return (MKNetworkOperationState)_state;
  221. }
  222. -(void) setState:(MKNetworkOperationState)newState {
  223. switch (newState) {
  224. case MKNetworkOperationStateReady:
  225. [self willChangeValueForKey:@"isReady"];
  226. break;
  227. case MKNetworkOperationStateExecuting:
  228. [self willChangeValueForKey:@"isReady"];
  229. [self willChangeValueForKey:@"isExecuting"];
  230. break;
  231. case MKNetworkOperationStateFinished:
  232. [self willChangeValueForKey:@"isExecuting"];
  233. [self willChangeValueForKey:@"isFinished"];
  234. break;
  235. }
  236. _state = newState;
  237. switch (newState) {
  238. case MKNetworkOperationStateReady:
  239. [self didChangeValueForKey:@"isReady"];
  240. break;
  241. case MKNetworkOperationStateExecuting:
  242. [self didChangeValueForKey:@"isReady"];
  243. [self didChangeValueForKey:@"isExecuting"];
  244. break;
  245. case MKNetworkOperationStateFinished:
  246. [self didChangeValueForKey:@"isExecuting"];
  247. [self didChangeValueForKey:@"isFinished"];
  248. break;
  249. }
  250. if(self.operationStateChangedHandler) {
  251. self.operationStateChangedHandler(newState);
  252. }
  253. }
  254. - (void)encodeWithCoder:(NSCoder *)encoder
  255. {
  256. [encoder encodeInteger:(NSInteger)self.stringEncoding forKey:@"stringEncoding"];
  257. [encoder encodeInteger:_postDataEncoding forKey:@"postDataEncoding"];
  258. [encoder encodeObject:self.uniqueId forKey:@"uniqueId"];
  259. [encoder encodeObject:self.request forKey:@"request"];
  260. [encoder encodeObject:self.response forKey:@"response"];
  261. [encoder encodeObject:self.fieldsToBePosted forKey:@"fieldsToBePosted"];
  262. [encoder encodeObject:self.filesToBePosted forKey:@"filesToBePosted"];
  263. [encoder encodeObject:self.dataToBePosted forKey:@"dataToBePosted"];
  264. [encoder encodeObject:self.username forKey:@"username"];
  265. [encoder encodeObject:self.password forKey:@"password"];
  266. [encoder encodeObject:self.clientCertificate forKey:@"clientCertificate"];
  267. [encoder encodeObject:self.clientCertificatePassword forKey:@"clientCertificatePassword"];
  268. [encoder encodeBool:self.shouldContinueWithInvalidCertificate forKey:@"shouldContinueWithInvalidCertificate"];
  269. #if TARGET_OS_IPHONE
  270. [encoder encodeObject:self.localNotification forKey:@"localNotification"];
  271. #endif
  272. self.state = MKNetworkOperationStateReady;
  273. [encoder encodeInt32:_state forKey:@"state"];
  274. [encoder encodeBool:self.isCancelled forKey:@"isCancelled"];
  275. [encoder encodeObject:self.mutableData forKey:@"mutableData"];
  276. [encoder encodeInteger:(NSInteger)self.downloadedDataSize forKey:@"downloadedDataSize"];
  277. [encoder encodeObject:self.downloadStreams forKey:@"downloadStreams"];
  278. [encoder encodeInteger:self.startPosition forKey:@"startPosition"];
  279. [encoder encodeInteger:self.credentialPersistence forKey:@"credentialPersistence"];
  280. }
  281. - (id)initWithCoder:(NSCoder *)decoder
  282. {
  283. self = [super init];
  284. if (self) {
  285. _imageCacheDuration = kMKNetworkKitDefaultImageCacheDuration;
  286. _imageHeadCacheDuration = kMKNetworkKitDefaultImageHeadRequestDuration;
  287. [self setStringEncoding:(NSStringEncoding)[decoder decodeIntegerForKey:@"stringEncoding"]];
  288. _postDataEncoding = (MKNKPostDataEncodingType) [decoder decodeIntegerForKey:@"postDataEncoding"];
  289. self.request = [decoder decodeObjectForKey:@"request"];
  290. self.uniqueId = [decoder decodeObjectForKey:@"uniqueId"];
  291. self.response = [decoder decodeObjectForKey:@"response"];
  292. self.fieldsToBePosted = [decoder decodeObjectForKey:@"fieldsToBePosted"];
  293. self.filesToBePosted = [decoder decodeObjectForKey:@"filesToBePosted"];
  294. self.dataToBePosted = [decoder decodeObjectForKey:@"dataToBePosted"];
  295. self.username = [decoder decodeObjectForKey:@"username"];
  296. self.password = [decoder decodeObjectForKey:@"password"];
  297. self.clientCertificate = [decoder decodeObjectForKey:@"clientCertificate"];
  298. self.clientCertificatePassword = [decoder decodeObjectForKey:@"clientCertificatePassword"];
  299. #if TARGET_OS_IPHONE
  300. self.localNotification = [decoder decodeObjectForKey:@"localNotification"];
  301. #endif
  302. [self setState:(MKNetworkOperationState)[decoder decodeInt32ForKey:@"state"]];
  303. self.isCancelled = [decoder decodeBoolForKey:@"isCancelled"];
  304. self.mutableData = [decoder decodeObjectForKey:@"mutableData"];
  305. self.downloadedDataSize = [decoder decodeIntegerForKey:@"downloadedDataSize"];
  306. self.downloadStreams = [decoder decodeObjectForKey:@"downloadStreams"];
  307. self.startPosition = [decoder decodeIntegerForKey:@"startPosition"];
  308. self.credentialPersistence = [decoder decodeIntegerForKey:@"credentialPersistence"];
  309. }
  310. return self;
  311. }
  312. - (id)copyWithZone:(NSZone *)zone
  313. {
  314. MKNetworkOperation *theCopy = [[[self class] allocWithZone:zone] init]; // use designated initializer
  315. theCopy.postDataEncoding = _postDataEncoding;
  316. [theCopy setStringEncoding:self.stringEncoding];
  317. [theCopy setUniqueId:[self.uniqueId copy]];
  318. [theCopy setConnection:[self.connection copy]];
  319. [theCopy setRequest:[self.request copy]];
  320. [theCopy setResponse:[self.response copy]];
  321. [theCopy setFieldsToBePosted:[self.fieldsToBePosted copy]];
  322. [theCopy setFilesToBePosted:[self.filesToBePosted copy]];
  323. [theCopy setDataToBePosted:[self.dataToBePosted copy]];
  324. [theCopy setUsername:[self.username copy]];
  325. [theCopy setPassword:[self.password copy]];
  326. [theCopy setClientCertificate:[self.clientCertificate copy]];
  327. [theCopy setResponseBlocks:[self.responseBlocks copy]];
  328. [theCopy setErrorBlocks:[self.errorBlocks copy]];
  329. [theCopy setErrorBlocksType2:[self.errorBlocksType2 copy]];
  330. [theCopy setState:self.state];
  331. [theCopy setIsCancelled:self.isCancelled];
  332. [theCopy setMutableData:[self.mutableData copy]];
  333. [theCopy setDownloadedDataSize:self.downloadedDataSize];
  334. [theCopy setNotModifiedHandlers:[self.notModifiedHandlers copy]];
  335. [theCopy setUploadProgressChangedHandlers:[self.uploadProgressChangedHandlers copy]];
  336. [theCopy setDownloadProgressChangedHandlers:[self.downloadProgressChangedHandlers copy]];
  337. [theCopy setDownloadStreams:[self.downloadStreams copy]];
  338. [theCopy setCachedResponse:[self.cachedResponse copy]];
  339. [theCopy setCacheHandlingBlock:self.cacheHandlingBlock];
  340. [theCopy setStartPosition:self.startPosition];
  341. [theCopy setCredentialPersistence:self.credentialPersistence];
  342. return theCopy;
  343. }
  344. -(void) dealloc {
  345. [_connection cancel];
  346. _connection = nil;
  347. }
  348. -(void) updateHandlersFromOperation:(MKNetworkOperation*) operation {
  349. [self.responseBlocks addObjectsFromArray:operation.responseBlocks];
  350. [self.errorBlocks addObjectsFromArray:operation.errorBlocks];
  351. [self.errorBlocksType2 addObjectsFromArray:operation.errorBlocksType2];
  352. [self.notModifiedHandlers addObjectsFromArray:operation.notModifiedHandlers];
  353. [self.uploadProgressChangedHandlers addObjectsFromArray:operation.uploadProgressChangedHandlers];
  354. [self.downloadProgressChangedHandlers addObjectsFromArray:operation.downloadProgressChangedHandlers];
  355. [self.downloadStreams addObjectsFromArray:operation.downloadStreams];
  356. }
  357. -(void) setCachedData:(NSData*) cachedData {
  358. self.cachedResponse = cachedData;
  359. [self operationSucceeded];
  360. }
  361. -(void) updateOperationBasedOnPreviousHeaders:(NSMutableDictionary*) headers {
  362. NSString *lastModified = headers[@"Last-Modified"];
  363. NSString *eTag = headers[@"ETag"];
  364. if(lastModified) {
  365. [self.request setValue:lastModified forHTTPHeaderField:@"IF-MODIFIED-SINCE"];
  366. }
  367. if(eTag) {
  368. [self.request setValue:eTag forHTTPHeaderField:@"IF-NONE-MATCH"];
  369. }
  370. }
  371. -(void) setUsername:(NSString*) username password:(NSString*) password {
  372. self.username = username;
  373. self.password = password;
  374. }
  375. -(void) setUsername:(NSString*) username password:(NSString*) password basicAuth:(BOOL) bYesOrNo {
  376. [self setUsername:username password:password];
  377. NSString *base64EncodedString = [[[NSString stringWithFormat:@"%@:%@", self.username, self.password] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
  378. [self setAuthorizationHeaderValue:base64EncodedString forAuthType:@"Basic"];
  379. }
  380. -(void) onCompletion:(MKNKResponseBlock) response onError:(MKNKErrorBlock) error {
  381. [self.responseBlocks addObject:[response copy]];
  382. [self.errorBlocks addObject:[error copy]];
  383. }
  384. -(void) addCompletionHandler:(MKNKResponseBlock)response errorHandler:(MKNKResponseErrorBlock)error {
  385. if(response)
  386. [self.responseBlocks addObject:[response copy]];
  387. if(error)
  388. [self.errorBlocksType2 addObject:[error copy]];
  389. }
  390. -(void) onNotModified:(MKNKVoidBlock)notModifiedBlock {
  391. [self.notModifiedHandlers addObject:[notModifiedBlock copy]];
  392. }
  393. -(void) onUploadProgressChanged:(MKNKProgressBlock) uploadProgressBlock {
  394. [self.uploadProgressChangedHandlers addObject:[uploadProgressBlock copy]];
  395. }
  396. -(void) onDownloadProgressChanged:(MKNKProgressBlock) downloadProgressBlock {
  397. [self.downloadProgressChangedHandlers addObject:[downloadProgressBlock copy]];
  398. }
  399. -(void) setUploadStream:(NSInputStream*) inputStream {
  400. #warning Method not tested yet.
  401. self.request.HTTPBodyStream = inputStream;
  402. }
  403. -(void) addDownloadStream:(NSOutputStream*) outputStream {
  404. [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  405. [self.downloadStreams addObject:outputStream];
  406. }
  407. - (id)initWithURLString:(NSString *)aURLString
  408. params:(NSDictionary *)params
  409. httpMethod:(NSString *)method
  410. {
  411. if((self = [super init])) {
  412. _imageCacheDuration = kMKNetworkKitDefaultImageCacheDuration;
  413. _imageHeadCacheDuration = kMKNetworkKitDefaultImageHeadRequestDuration;
  414. self.responseBlocks = [NSMutableArray array];
  415. self.errorBlocks = [NSMutableArray array];
  416. self.errorBlocksType2 = [NSMutableArray array];
  417. self.filesToBePosted = [NSMutableArray array];
  418. self.dataToBePosted = [NSMutableArray array];
  419. self.fieldsToBePosted = [NSMutableDictionary dictionary];
  420. self.notModifiedHandlers = [NSMutableArray array];
  421. self.uploadProgressChangedHandlers = [NSMutableArray array];
  422. self.downloadProgressChangedHandlers = [NSMutableArray array];
  423. self.downloadStreams = [NSMutableArray array];
  424. self.credentialPersistence = NSURLCredentialPersistenceForSession;
  425. NSURL *finalURL = nil;
  426. if(params)
  427. self.fieldsToBePosted = [params mutableCopy];
  428. self.stringEncoding = NSUTF8StringEncoding; // use a delegate to get these values later
  429. if ([method isEqualToString:@"GET"])
  430. self.cacheHeaders = [NSMutableDictionary dictionary];
  431. if (([method isEqualToString:@"GET"] ||
  432. [method isEqualToString:@"DELETE"]) && (params && [params count] > 0)) {
  433. finalURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", aURLString,
  434. [self encodedPostDataString]]];
  435. } else {
  436. finalURL = [NSURL URLWithString:aURLString];
  437. }
  438. self.request = [NSMutableURLRequest requestWithURL:finalURL
  439. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  440. timeoutInterval:kMKNetworkKitRequestTimeOutInSeconds];
  441. [self.request setHTTPMethod:method];
  442. [self.request setValue:[NSString stringWithFormat:@"%@, en-us",
  443. [[NSLocale preferredLanguages] componentsJoinedByString:@", "]
  444. ] forHTTPHeaderField:@"Accept-Language"];
  445. if (([method isEqualToString:@"POST"] ||
  446. [method isEqualToString:@"PUT"]) && (params && [params count] > 0)) {
  447. self.postDataEncoding = MKNKPostDataEncodingTypeURL;
  448. }
  449. self.state = MKNetworkOperationStateReady;
  450. }
  451. return self;
  452. }
  453. -(void) addHeaders:(NSDictionary*) headersDictionary {
  454. [headersDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  455. [self.request addValue:obj forHTTPHeaderField:key];
  456. }];
  457. }
  458. -(void) setAuthorizationHeaderValue:(NSString*) token forAuthType:(NSString*) authType {
  459. [self.request setValue:[NSString stringWithFormat:@"%@ %@", authType, token]
  460. forHTTPHeaderField:@"Authorization"];
  461. }
  462. /*
  463. Printing a MKNetworkOperation object is printed in curl syntax
  464. */
  465. -(NSString*) description {
  466. NSMutableString *displayString = [NSMutableString stringWithFormat:@"%@\nRequest\n-------\n%@",
  467. [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]],
  468. [self curlCommandLineString]];
  469. NSString *responseString = [self responseString];
  470. if([responseString length] > 0) {
  471. [displayString appendFormat:@"\n--------\nResponse\n--------\n%@\n", responseString];
  472. }
  473. return displayString;
  474. }
  475. -(NSString*) curlCommandLineString
  476. {
  477. __block NSMutableString *displayString = [NSMutableString stringWithFormat:@"curl -X %@", self.request.HTTPMethod];
  478. if([self.filesToBePosted count] == 0 && [self.dataToBePosted count] == 0) {
  479. [[self.request allHTTPHeaderFields] enumerateKeysAndObjectsUsingBlock:^(id key, id val, BOOL *stop)
  480. {
  481. [displayString appendFormat:@" -H \"%@: %@\"", key, val];
  482. }];
  483. }
  484. [displayString appendFormat:@" \"%@\"", self.url];
  485. if ([self.request.HTTPMethod isEqualToString:@"POST"] ||
  486. [self.request.HTTPMethod isEqualToString:@"PUT"] ||
  487. [self.request.HTTPMethod isEqualToString:@"PATCH"]) {
  488. NSString *option = [self.filesToBePosted count] == 0 ? @"-d" : @"-F";
  489. if(self.postDataEncoding == MKNKPostDataEncodingTypeURL) {
  490. [self.fieldsToBePosted enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  491. [displayString appendFormat:@" %@ \"%@=%@\"", option, key, obj];
  492. }];
  493. } else {
  494. [displayString appendFormat:@" -d \"%@\"", [self encodedPostDataString]];
  495. }
  496. [self.filesToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  497. NSDictionary *thisFile = (NSDictionary*) obj;
  498. [displayString appendFormat:@" -F \"%@=@%@;type=%@\"", thisFile[@"name"],
  499. thisFile[@"filepath"], thisFile[@"mimetype"]];
  500. }];
  501. /* Not sure how to do this via curl
  502. [self.dataToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  503. NSDictionary *thisData = (NSDictionary*) obj;
  504. [displayString appendFormat:@" --data-binary \"%@\"", [thisData objectForKey:@"data"]];
  505. }];*/
  506. }
  507. return displayString;
  508. }
  509. -(void) addData:(NSData*) data forKey:(NSString*) key {
  510. [self addData:data forKey:key mimeType:@"application/octet-stream" fileName:@"file"];
  511. }
  512. -(void) addData:(NSData*) data forKey:(NSString*) key mimeType:(NSString*) mimeType fileName:(NSString*) fileName {
  513. if ([self.request.HTTPMethod isEqualToString:@"GET"]) {
  514. [self.request setHTTPMethod:@"POST"];
  515. }
  516. NSDictionary *dict = @{@"data": data,
  517. @"name": key,
  518. @"mimetype": mimeType,
  519. @"filename": fileName};
  520. [self.dataToBePosted addObject:dict];
  521. }
  522. -(void) addFile:(NSString*) filePath forKey:(NSString*) key {
  523. [self addFile:filePath forKey:key mimeType:@"application/octet-stream"];
  524. }
  525. -(void) addFile:(NSString*) filePath forKey:(NSString*) key mimeType:(NSString*) mimeType {
  526. if ([self.request.HTTPMethod isEqualToString:@"GET"]) {
  527. [self.request setHTTPMethod:@"POST"];
  528. }
  529. NSDictionary *dict = @{@"filepath": filePath,
  530. @"name": key,
  531. @"mimetype": mimeType};
  532. [self.filesToBePosted addObject:dict];
  533. }
  534. -(NSData*) bodyData {
  535. if([self.filesToBePosted count] == 0 && [self.dataToBePosted count] == 0) {
  536. return [[self encodedPostDataString] dataUsingEncoding:self.stringEncoding];
  537. }
  538. NSString *boundary = @"0xKhTmLbOuNdArY";
  539. NSMutableData *body = [NSMutableData data];
  540. __block NSUInteger postLength = 0;
  541. [self.fieldsToBePosted enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  542. NSString *thisFieldString = [NSString stringWithFormat:
  543. @"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@",
  544. boundary, key, obj];
  545. [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]];
  546. [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]];
  547. }];
  548. [self.filesToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  549. NSDictionary *thisFile = (NSDictionary*) obj;
  550. NSString *thisFieldString = [NSString stringWithFormat:
  551. @"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\nContent-Transfer-Encoding: binary\r\n\r\n",
  552. boundary,
  553. thisFile[@"name"],
  554. [thisFile[@"filepath"] lastPathComponent],
  555. thisFile[@"mimetype"]];
  556. [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]];
  557. [body appendData: [NSData dataWithContentsOfFile:thisFile[@"filepath"]]];
  558. [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]];
  559. }];
  560. [self.dataToBePosted enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  561. NSDictionary *thisDataObject = (NSDictionary*) obj;
  562. NSString *thisFieldString = [NSString stringWithFormat:
  563. @"--%@\r\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: %@\r\nContent-Transfer-Encoding: binary\r\n\r\n",
  564. boundary,
  565. thisDataObject[@"name"],
  566. thisDataObject[@"filename"],
  567. thisDataObject[@"mimetype"]];
  568. [body appendData:[thisFieldString dataUsingEncoding:[self stringEncoding]]];
  569. [body appendData:thisDataObject[@"data"]];
  570. [body appendData:[@"\r\n" dataUsingEncoding:[self stringEncoding]]];
  571. }];
  572. if (postLength >= 1)
  573. [self.request setValue:[NSString stringWithFormat:@"%lu", (unsigned long) postLength] forHTTPHeaderField:@"Content-Length"];
  574. [body appendData: [[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:self.stringEncoding]];
  575. NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
  576. if(([self.filesToBePosted count] > 0) || ([self.dataToBePosted count] > 0)) {
  577. [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, boundary]
  578. forHTTPHeaderField:@"Content-Type"];
  579. [self.request setValue:[NSString stringWithFormat:@"%lu", (unsigned long) [body length]] forHTTPHeaderField:@"Content-Length"];
  580. }
  581. return body;
  582. }
  583. -(void) setCacheHandler:(MKNKResponseBlock) cacheHandler {
  584. self.cacheHandlingBlock = cacheHandler;
  585. }
  586. #pragma mark -
  587. #pragma Main method
  588. -(void) main {
  589. @autoreleasepool {
  590. [self start];
  591. }
  592. }
  593. -(void) endBackgroundTask {
  594. #if TARGET_OS_IPHONE
  595. dispatch_async(dispatch_get_main_queue(), ^{
  596. if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
  597. [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
  598. self.backgroundTaskId = UIBackgroundTaskInvalid;
  599. }
  600. });
  601. #endif
  602. }
  603. - (void) start
  604. {
  605. #if TARGET_OS_IPHONE
  606. self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  607. dispatch_async(dispatch_get_main_queue(), ^{
  608. if (self.backgroundTaskId != UIBackgroundTaskInvalid)
  609. {
  610. [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
  611. self.backgroundTaskId = UIBackgroundTaskInvalid;
  612. [self cancel];
  613. }
  614. });
  615. }];
  616. #endif
  617. if(!self.isCancelled) {
  618. if (([self.request.HTTPMethod isEqualToString:@"POST"] ||
  619. [self.request.HTTPMethod isEqualToString:@"PUT"] ||
  620. [self.request.HTTPMethod isEqualToString:@"PATCH"]) && !self.request.HTTPBodyStream) {
  621. [self.request setHTTPBody:[self bodyData]];
  622. }
  623. dispatch_async(dispatch_get_main_queue(), ^{
  624. self.connection = [[NSURLConnection alloc] initWithRequest:self.request
  625. delegate:self
  626. startImmediately:NO];
  627. [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
  628. forMode:NSRunLoopCommonModes];
  629. [self.connection start];
  630. });
  631. self.state = MKNetworkOperationStateExecuting;
  632. }
  633. else {
  634. self.state = MKNetworkOperationStateFinished;
  635. [self endBackgroundTask];
  636. }
  637. }
  638. #pragma -
  639. #pragma mark NSOperation stuff
  640. - (BOOL)isConcurrent
  641. {
  642. return YES;
  643. }
  644. - (BOOL)isReady {
  645. return (self.state == MKNetworkOperationStateReady && [super isReady]);
  646. }
  647. - (BOOL)isFinished
  648. {
  649. return (self.state == MKNetworkOperationStateFinished);
  650. }
  651. - (BOOL)isExecuting {
  652. return (self.state == MKNetworkOperationStateExecuting);
  653. }
  654. -(void) cancel {
  655. if([self isFinished])
  656. return;
  657. @synchronized(self) {
  658. self.isCancelled = YES;
  659. [self.connection cancel];
  660. [self.responseBlocks removeAllObjects];
  661. self.responseBlocks = nil;
  662. [self.errorBlocks removeAllObjects];
  663. self.errorBlocks = nil;
  664. [self.errorBlocksType2 removeAllObjects];
  665. self.errorBlocksType2 = nil;
  666. [self.notModifiedHandlers removeAllObjects];
  667. self.notModifiedHandlers = nil;
  668. [self.uploadProgressChangedHandlers removeAllObjects];
  669. self.uploadProgressChangedHandlers = nil;
  670. [self.downloadProgressChangedHandlers removeAllObjects];
  671. self.downloadProgressChangedHandlers = nil;
  672. for(NSOutputStream *stream in self.downloadStreams)
  673. [stream close];
  674. [self.downloadStreams removeAllObjects];
  675. self.downloadStreams = nil;
  676. self.authHandler = nil;
  677. self.mutableData = nil;
  678. self.downloadedDataSize = 0;
  679. self.cacheHandlingBlock = nil;
  680. if(self.state == MKNetworkOperationStateExecuting)
  681. self.state = MKNetworkOperationStateFinished; // This notifies the queue and removes the operation.
  682. // if the operation is not removed, the spinner continues to spin, not a good UX
  683. [self endBackgroundTask];
  684. }
  685. [super cancel];
  686. }
  687. #pragma mark -
  688. #pragma mark NSURLConnection delegates
  689. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  690. self.state = MKNetworkOperationStateFinished;
  691. self.mutableData = nil;
  692. self.downloadedDataSize = 0;
  693. for(NSOutputStream *stream in self.downloadStreams)
  694. [stream close];
  695. [self operationFailedWithError:error];
  696. [self endBackgroundTask];
  697. }
  698. // https://developer.apple.com/library/mac/#documentation/security/conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html
  699. OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data, // 5
  700. SecIdentityRef *outIdentity,
  701. SecTrustRef *outTrust,
  702. CFStringRef keyPassword)
  703. {
  704. OSStatus securityError = errSecSuccess;
  705. const void *keys[] = { kSecImportExportPassphrase };
  706. const void *values[] = { keyPassword };
  707. CFDictionaryRef optionsDictionary = NULL;
  708. /* Create a dictionary containing the passphrase if one
  709. was specified. Otherwise, create an empty dictionary. */
  710. optionsDictionary = CFDictionaryCreate(
  711. NULL, keys,
  712. values, (keyPassword ? 1 : 0),
  713. NULL, NULL); // 6
  714. CFArrayRef items = NULL;
  715. securityError = SecPKCS12Import(inPKCS12Data,
  716. optionsDictionary,
  717. &items); // 7
  718. //
  719. if (securityError == 0) { // 8
  720. CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
  721. const void *tempIdentity = NULL;
  722. tempIdentity = CFDictionaryGetValue (myIdentityAndTrust,
  723. kSecImportItemIdentity);
  724. CFRetain(tempIdentity);
  725. *outIdentity = (SecIdentityRef)tempIdentity;
  726. const void *tempTrust = NULL;
  727. tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
  728. CFRetain(tempTrust);
  729. *outTrust = (SecTrustRef)tempTrust;
  730. }
  731. if (optionsDictionary)
  732. CFRelease(optionsDictionary); // 9
  733. if (items)
  734. CFRelease(items);
  735. return securityError;
  736. }
  737. - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  738. if (challenge.previousFailureCount == 0) {
  739. if (((challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodDefault) ||
  740. (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic) ||
  741. (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest) ||
  742. (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM)) &&
  743. (self.username && self.password))
  744. {
  745. // for NTLM, we will assume user name to be of the form "domain\\username"
  746. NSURLCredential *credential = [NSURLCredential credentialWithUser:self.username
  747. password:self.password
  748. persistence:self.credentialPersistence];
  749. [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
  750. }
  751. else if ((challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) && self.clientCertificate) {
  752. NSError *error = nil;
  753. NSData *certData = [[NSData alloc] initWithContentsOfFile:self.clientCertificate options:0 error:&error];
  754. SecIdentityRef identity;
  755. SecTrustRef trust;
  756. OSStatus status = extractIdentityAndTrust((__bridge CFDataRef) certData, &identity, &trust, (__bridge CFStringRef) self.clientCertificatePassword);
  757. if(status == errSecSuccess) {
  758. SecCertificateRef certificate;
  759. SecIdentityCopyCertificate(identity, &certificate);
  760. const void *certs[] = { certificate };
  761. CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);
  762. NSArray *certificatesForCredential = (__bridge NSArray *)certsArray;
  763. NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity
  764. certificates:certificatesForCredential
  765. persistence:NSURLCredentialPersistencePermanent];
  766. [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
  767. CFRelease(identity);
  768. CFRelease(certificate);
  769. CFRelease(certsArray);
  770. } else {
  771. [challenge.sender cancelAuthenticationChallenge:challenge];
  772. }
  773. }
  774. else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
  775. if(challenge.previousFailureCount < 5) {
  776. self.serverTrust = challenge.protectionSpace.serverTrust;
  777. SecTrustResultType result;
  778. SecTrustEvaluate(self.serverTrust, &result);
  779. if(result == kSecTrustResultProceed ||
  780. result == kSecTrustResultUnspecified || //The cert is valid, but user has not explicitly accepted/denied. Ok to proceed (Ch 15: iOS PTL :Pg 269)
  781. result == kSecTrustResultRecoverableTrustFailure //The cert is invalid, but is invalid because of name mismatch. Ok to proceed (Ch 15: iOS PTL :Pg 269)
  782. ) {
  783. [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
  784. }
  785. else if(result == kSecTrustResultConfirm) {
  786. if(self.shouldContinueWithInvalidCertificate) {
  787. // Cert not trusted, but user is OK with that
  788. DLog(@"Certificate is not trusted, but self.shouldContinueWithInvalidCertificate is YES");
  789. [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
  790. } else {
  791. DLog(@"Certificate is not trusted, continuing without credentials. Might result in 401 Unauthorized");
  792. [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
  793. }
  794. }
  795. else {
  796. // invalid or revoked certificate
  797. if(self.shouldContinueWithInvalidCertificate) {
  798. DLog(@"Certificate is invalid, but self.shouldContinueWithInvalidCertificate is YES");
  799. [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
  800. } else {
  801. DLog(@"Certificate is invalid, continuing without credentials. Might result in 401 Unauthorized");
  802. [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
  803. }
  804. }
  805. } else {
  806. [challenge.sender cancelAuthenticationChallenge:challenge];
  807. }
  808. }
  809. else if (self.authHandler) {
  810. // forward the authentication to the view controller that created this operation
  811. // If this happens for NSURLAuthenticationMethodHTMLForm, you have to
  812. // do some shit work like showing a modal webview controller and close it after authentication.
  813. // I HATE THIS.
  814. self.authHandler(challenge);
  815. }
  816. else {
  817. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  818. }
  819. } else {
  820. // apple proposes to cancel authentication, which results in NSURLErrorDomain error -1012, but we prefer to trigger a 401
  821. // [[challenge sender] cancelAuthenticationChallenge:challenge];
  822. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  823. }
  824. }
  825. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  826. NSUInteger size = [self.response expectedContentLength] < 0 ? 0 : (NSUInteger)[self.response expectedContentLength];
  827. self.response = (NSHTTPURLResponse*) response;
  828. // dont' save data if the operation was created to download directly to a stream.
  829. if([self.downloadStreams count] == 0)
  830. self.mutableData = [NSMutableData dataWithCapacity:size];
  831. else
  832. self.mutableData = nil;
  833. for(NSOutputStream *stream in self.downloadStreams)
  834. [stream open];
  835. NSDictionary *httpHeaders = [self.response allHeaderFields];
  836. // if you attach a stream to the operation, MKNetworkKit will not cache the response.
  837. // Streams are usually "big data chunks" that doesn't need caching anyways.
  838. if([self.request.HTTPMethod isEqualToString:@"GET"] && [self.downloadStreams count] == 0) {
  839. // We have all this complicated cache handling since NSURLRequestReloadRevalidatingCacheData is not implemented
  840. // do cache processing only if the request is a "GET" method
  841. NSString *lastModified = httpHeaders[@"Last-Modified"];
  842. NSString *eTag = httpHeaders[@"ETag"];
  843. NSString *expiresOn = httpHeaders[@"Expires"];
  844. NSString *contentType = httpHeaders[@"Content-Type"];
  845. // if contentType is image,
  846. NSDate *expiresOnDate = nil;
  847. if([contentType rangeOfString:@"image"].location != NSNotFound) {
  848. // For images let's assume a expiry date of 7 days if there is no eTag or Last Modified.
  849. if(!eTag && !lastModified)
  850. expiresOnDate = [[NSDate date] dateByAddingTimeInterval:_imageCacheDuration];
  851. // expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultImageCacheDuration];
  852. else
  853. expiresOnDate = [[NSDate date] dateByAddingTimeInterval:_imageHeadCacheDuration];
  854. // expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultImageHeadRequestDuration];
  855. }
  856. NSString *cacheControl = httpHeaders[@"Cache-Control"]; // max-age, must-revalidate, no-cache
  857. NSArray *cacheControlEntities = [cacheControl componentsSeparatedByString:@","];
  858. for(NSString *substring in cacheControlEntities) {
  859. if([substring rangeOfString:@"max-age"].location != NSNotFound) {
  860. // do some processing to calculate expiresOn
  861. NSString *maxAge = nil;
  862. NSArray *array = [substring componentsSeparatedByString:@"="];
  863. if([array count] > 1)
  864. maxAge = array[1];
  865. expiresOnDate = [[NSDate date] dateByAddingTimeInterval:[maxAge intValue]];
  866. }
  867. if([substring rangeOfString:@"no-cache"].location != NSNotFound) {
  868. // Don't cache this request
  869. expiresOnDate = [[NSDate date] dateByAddingTimeInterval:kMKNetworkKitDefaultCacheDuration];
  870. }
  871. }
  872. // if there was a cacheControl entity, we would have a expiresOnDate that is not nil.
  873. // "Cache-Control" headers take precedence over "Expires" headers
  874. if(expiresOnDate)
  875. expiresOn = [expiresOnDate rfc1123String];
  876. // now remember lastModified, eTag and expires for this request in cache
  877. if(expiresOn)
  878. (self.cacheHeaders)[@"Expires"] = expiresOn;
  879. if(lastModified)
  880. (self.cacheHeaders)[@"Last-Modified"] = lastModified;
  881. if(eTag)
  882. (self.cacheHeaders)[@"ETag"] = eTag;
  883. }
  884. }
  885. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  886. if (self.downloadedDataSize == 0) {
  887. // This is the first batch of data
  888. // Check for a range header and make changes as neccesary
  889. NSString *rangeString = [[self request] valueForHTTPHeaderField:@"Range"];
  890. if ([rangeString hasPrefix:@"bytes="] && [rangeString hasSuffix:@"-"]) {
  891. NSString *bytesText = [rangeString substringWithRange:NSMakeRange(6, [rangeString length] - 7)];
  892. self.startPosition = [bytesText integerValue];
  893. self.downloadedDataSize = self.startPosition;
  894. DLog(@"Resuming at %lu bytes", (unsigned long) self.startPosition);
  895. }
  896. }
  897. if([self.downloadStreams count] == 0)
  898. [self.mutableData appendData:data];
  899. for(NSOutputStream *stream in self.downloadStreams) {
  900. if ([stream hasSpaceAvailable]) {
  901. const uint8_t *dataBuffer = [data bytes];
  902. [stream write:&dataBuffer[0] maxLength:[data length]];
  903. }
  904. }
  905. self.downloadedDataSize += [data length];
  906. for(MKNKProgressBlock downloadProgressBlock in self.downloadProgressChangedHandlers) {
  907. if([self.response expectedContentLength] > 0) {
  908. double progress = (double)(self.downloadedDataSize) / (double)(self.startPosition + [self.response expectedContentLength]);
  909. downloadProgressBlock(progress);
  910. }
  911. }
  912. }
  913. - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten
  914. totalBytesWritten:(NSInteger)totalBytesWritten
  915. totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
  916. for(MKNKProgressBlock uploadProgressBlock in self.uploadProgressChangedHandlers) {
  917. if(totalBytesExpectedToWrite > 0) {
  918. uploadProgressBlock(((double)totalBytesWritten/(double)totalBytesExpectedToWrite));
  919. }
  920. }
  921. }
  922. // http://stackoverflow.com/questions/1446509/handling-redirects-correctly-with-nsurlconnection
  923. - (NSURLRequest *)connection: (NSURLConnection *)inConnection
  924. willSendRequest: (NSURLRequest *)inRequest
  925. redirectResponse: (NSURLResponse *)inRedirectResponse;
  926. {
  927. if (inRedirectResponse) {
  928. NSMutableURLRequest *r = [self.request mutableCopy];
  929. [r setURL: [inRequest URL]];
  930. return r;
  931. } else {
  932. return inRequest;
  933. }
  934. }
  935. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  936. if([self isCancelled])
  937. return;
  938. self.state = MKNetworkOperationStateFinished;
  939. for(NSOutputStream *stream in self.downloadStreams)
  940. [stream close];
  941. if (self.response.statusCode >= 200 && self.response.statusCode < 300 && ![self isCancelled]) {
  942. self.cachedResponse = nil; // remove cached data
  943. [self notifyCache];
  944. [self operationSucceeded];
  945. }
  946. if (self.response.statusCode >= 300 && self.response.statusCode < 400) {
  947. if(self.response.statusCode == 301) {
  948. DLog(@"%@ has moved to %@", self.url, [self.response.URL absoluteString]);
  949. }
  950. else if(self.response.statusCode == 304) {
  951. for(MKNKVoidBlock notModifiedBlock in self.notModifiedHandlers) {
  952. notModifiedBlock();
  953. }
  954. }
  955. else if(self.response.statusCode == 307) {
  956. DLog(@"%@ temporarily redirected", self.url);
  957. }
  958. else {
  959. DLog(@"%@ returned status %d", self.url, (int) self.response.statusCode);
  960. }
  961. } else if (self.response.statusCode >= 400 && ![self isCancelled]) {
  962. [self operationFailedWithError:[NSError errorWithDomain:NSURLErrorDomain
  963. code:self.response.statusCode
  964. userInfo:self.response.allHeaderFields]];
  965. }
  966. [self endBackgroundTask];
  967. }
  968. #pragma mark -
  969. #pragma mark Our methods to get data
  970. -(NSData*) responseData {
  971. if([self isFinished])
  972. return self.mutableData;
  973. else if(self.cachedResponse)
  974. return self.cachedResponse;
  975. else
  976. return nil;
  977. }
  978. -(NSString*)responseString {
  979. return [self responseStringWithEncoding:self.stringEncoding];
  980. }
  981. -(NSString*) responseStringWithEncoding:(NSStringEncoding) encoding {
  982. return [[NSString alloc] initWithData:[self responseData] encoding:encoding];
  983. }
  984. #if TARGET_OS_IPHONE
  985. -(UIImage*) responseImage {
  986. return [UIImage imageWithData:[self responseData]];
  987. }
  988. -(void) decompressedResponseImageOfSize:(CGSize) size completionHandler:(void (^)(UIImage *decompressedImage)) imageDecompressionHandler {
  989. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  990. __block CGSize targetSize = size;
  991. UIImage *image = [self responseImage];
  992. CGImageRef imageRef = image.CGImage;
  993. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  994. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
  995. BOOL sameSize = NO;
  996. if (CGSizeEqualToSize(targetSize, CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)))) {
  997. targetSize = CGSizeMake(1, 1);
  998. sameSize = YES;
  999. }
  1000. size_t imageWidth = (size_t)targetSize.width;
  1001. size_t imageHeight = (size_t)targetSize.height;
  1002. CGContextRef context = CGBitmapContextCreate(NULL,
  1003. imageWidth,
  1004. imageHeight,
  1005. 8,
  1006. // Just always return width * 4 will be enough
  1007. imageWidth * 4,
  1008. // System only supports RGB, set explicitly
  1009. colorSpace,
  1010. // Makes system don't need to do extra conversion when displayed.
  1011. alphaInfo | kCGBitmapByteOrder32Little);
  1012. CGColorSpaceRelease(colorSpace);
  1013. if (!context) {
  1014. return;
  1015. }
  1016. CGRect rect = (CGRect){CGPointZero, {imageWidth, imageHeight}};
  1017. CGContextDrawImage(context, rect, imageRef);
  1018. if (sameSize) {
  1019. CGContextRelease(context);
  1020. dispatch_async(dispatch_get_main_queue(), ^{
  1021. imageDecompressionHandler(image);
  1022. });
  1023. return;
  1024. }
  1025. CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
  1026. CGContextRelease(context);
  1027. static float scale = 0.0f;
  1028. static dispatch_once_t onceToken;
  1029. dispatch_once(&onceToken, ^{
  1030. scale = [UIScreen mainScreen].scale;
  1031. });
  1032. UIImage *decompressedImage = [[UIImage alloc] initWithCGImage:decompressedImageRef scale:scale orientation:image.imageOrientation];
  1033. CGImageRelease(decompressedImageRef);
  1034. dispatch_async(dispatch_get_main_queue(), ^{
  1035. imageDecompressionHandler(decompressedImage);
  1036. });
  1037. });
  1038. }
  1039. #elif TARGET_OS_MAC
  1040. -(NSImage*) responseImage {
  1041. return [[NSImage alloc] initWithData:[self responseData]];
  1042. }
  1043. -(NSXMLDocument*) responseXML {
  1044. return [[NSXMLDocument alloc] initWithData:[self responseData] options:0 error:nil];
  1045. }
  1046. #endif
  1047. -(id) responseJSON {
  1048. if([self responseData] == nil) return nil;
  1049. NSError *error = nil;
  1050. id returnValue = [NSJSONSerialization JSONObjectWithData:[self responseData] options:0 error:&error];
  1051. if(error) DLog(@"JSON Parsing Error: %@", error);
  1052. return returnValue;
  1053. }
  1054. -(void) responseJSONWithCompletionHandler:(void (^)(id jsonObject)) jsonDecompressionHandler {
  1055. if([self responseData] == nil) {
  1056. jsonDecompressionHandler(nil);
  1057. return;
  1058. }
  1059. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1060. NSError *error = nil;
  1061. id returnValue = [NSJSONSerialization JSONObjectWithData:[self responseData] options:0 error:&error];
  1062. if(error) {
  1063. DLog(@"JSON Parsing Error: %@", error);
  1064. jsonDecompressionHandler(nil);
  1065. return;
  1066. }
  1067. dispatch_async(dispatch_get_main_queue(), ^{
  1068. jsonDecompressionHandler(returnValue);
  1069. });
  1070. });
  1071. }
  1072. #pragma mark -
  1073. #pragma mark Overridable methods
  1074. -(void) operationSucceeded {
  1075. for(MKNKResponseBlock responseBlock in self.responseBlocks)
  1076. responseBlock(self);
  1077. }
  1078. -(void) showLocalNotification {
  1079. #if TARGET_OS_IPHONE
  1080. if(self.localNotification) {
  1081. [[UIApplication sharedApplication] presentLocalNotificationNow:self.localNotification];
  1082. } else if(self.shouldShowLocalNotificationOnError) {
  1083. UILocalNotification *localNotification = [[UILocalNotification alloc] init];
  1084. localNotification.alertBody = [self.error localizedDescription];
  1085. localNotification.alertAction = NSLocalizedString(@"Dismiss", @"");
  1086. [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
  1087. }
  1088. #endif
  1089. }
  1090. -(void) operationFailedWithError:(NSError*) error {
  1091. self.error = error;
  1092. DLog(@"%@, [%@]", self, [self.error localizedDescription]);
  1093. for(MKNKErrorBlock errorBlock in self.errorBlocks)
  1094. errorBlock(error);
  1095. for(MKNKResponseErrorBlock errorBlock in self.errorBlocksType2)
  1096. errorBlock(self, error);
  1097. #if TARGET_OS_IPHONE
  1098. DLog(@"State: %d", [[UIApplication sharedApplication] applicationState]);
  1099. if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  1100. [self showLocalNotification];
  1101. #endif
  1102. }
  1103. @end