No Description

GTMSessionFetcher.h 60KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. /* Copyright 2014 Google Inc. All rights reserved.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. // GTMSessionFetcher is a wrapper around NSURLSession for http operations.
  16. //
  17. // What does this offer on top of of NSURLSession?
  18. //
  19. // - Block-style callbacks for useful functionality like progress rather
  20. // than delegate methods.
  21. // - Out-of-process uploads and downloads using NSURLSession, including
  22. // management of fetches after relaunch.
  23. // - Integration with GTMAppAuth for invisible management and refresh of
  24. // authorization tokens.
  25. // - Pretty-printed http logging.
  26. // - Cookies handling that does not interfere with or get interfered with
  27. // by WebKit cookies or on Mac by Safari and other apps.
  28. // - Credentials handling for the http operation.
  29. // - Rate-limiting and cookie grouping when fetchers are created with
  30. // GTMSessionFetcherService.
  31. //
  32. // If the bodyData or bodyFileURL property is set, then a POST request is assumed.
  33. //
  34. // Each fetcher is assumed to be for a one-shot fetch request; don't reuse the object
  35. // for a second fetch.
  36. //
  37. // The fetcher will be self-retained as long as a connection is pending.
  38. //
  39. // To keep user activity private, URLs must have an https scheme (unless the property
  40. // allowedInsecureSchemes is set to permit the scheme.)
  41. //
  42. // Callbacks will be released when the fetch completes or is stopped, so there is no need
  43. // to use weak self references in the callback blocks.
  44. //
  45. // Sample usage:
  46. //
  47. // _fetcherService = [[GTMSessionFetcherService alloc] init];
  48. //
  49. // GTMSessionFetcher *myFetcher = [_fetcherService fetcherWithURLString:myURLString];
  50. // myFetcher.retryEnabled = YES;
  51. // myFetcher.comment = @"First profile image";
  52. //
  53. // // Optionally specify a file URL or NSData for the request body to upload.
  54. // myFetcher.bodyData = [postString dataUsingEncoding:NSUTF8StringEncoding];
  55. //
  56. // [myFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  57. // if (error != nil) {
  58. // // Server status code or network error.
  59. // //
  60. // // If the domain is kGTMSessionFetcherStatusDomain then the error code
  61. // // is a failure status from the server.
  62. // } else {
  63. // // Fetch succeeded.
  64. // }
  65. // }];
  66. //
  67. // There is also a beginFetch call that takes a pointer and selector for the completion handler;
  68. // a pointer and selector is a better style when the callback is a substantial, separate method.
  69. //
  70. // NOTE: Fetches may retrieve data from the server even though the server
  71. // returned an error, so the criteria for success is a non-nil error.
  72. // The completion handler is called when the server status is >= 300 with an NSError
  73. // having domain kGTMSessionFetcherStatusDomain and code set to the server status.
  74. //
  75. // Status codes are at <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
  76. //
  77. //
  78. // Background session support:
  79. //
  80. // Out-of-process uploads and downloads may be created by setting the fetcher's
  81. // useBackgroundSession property. Data to be uploaded should be provided via
  82. // the uploadFileURL property; the download destination should be specified with
  83. // the destinationFileURL. NOTE: Background upload files should be in a location
  84. // that will be valid even after the device is restarted, so the file should not
  85. // be uploaded from a system temporary or cache directory.
  86. //
  87. // Background session transfers are slower, and should typically be used only
  88. // for very large downloads or uploads (hundreds of megabytes).
  89. //
  90. // When background sessions are used in iOS apps, the application delegate must
  91. // pass through the parameters from UIApplicationDelegate's
  92. // application:handleEventsForBackgroundURLSession:completionHandler: to the
  93. // fetcher class.
  94. //
  95. // When the application has been relaunched, it may also create a new fetcher
  96. // instance to handle completion of the transfers.
  97. //
  98. // - (void)application:(UIApplication *)application
  99. // handleEventsForBackgroundURLSession:(NSString *)identifier
  100. // completionHandler:(void (^)())completionHandler {
  101. // // Application was re-launched on completing an out-of-process download.
  102. //
  103. // // Pass the URLSession info related to this re-launch to the fetcher class.
  104. // [GTMSessionFetcher application:application
  105. // handleEventsForBackgroundURLSession:identifier
  106. // completionHandler:completionHandler];
  107. //
  108. // // Get a fetcher related to this re-launch and re-hook up a completionHandler to it.
  109. // GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithSessionIdentifier:identifier];
  110. // NSURL *destinationFileURL = fetcher.destinationFileURL;
  111. // fetcher.completionHandler = ^(NSData *data, NSError *error) {
  112. // [self downloadCompletedToFile:destinationFileURL error:error];
  113. // };
  114. // }
  115. //
  116. //
  117. // Threading and queue support:
  118. //
  119. // Networking always happens on a background thread; there is no advantage to
  120. // changing thread or queue to create or start a fetcher.
  121. //
  122. // Callbacks are run on the main thread; alternatively, the app may set the
  123. // fetcher's callbackQueue to a dispatch queue.
  124. //
  125. // Once the fetcher's beginFetch method has been called, the fetcher's methods and
  126. // properties may be accessed from any thread.
  127. //
  128. // Downloading to disk:
  129. //
  130. // To have downloaded data saved directly to disk, specify a file URL for the
  131. // destinationFileURL property.
  132. //
  133. // HTTP methods and headers:
  134. //
  135. // Alternative HTTP methods, like PUT, and custom headers can be specified by
  136. // creating the fetcher with an appropriate NSMutableURLRequest.
  137. //
  138. //
  139. // Caching:
  140. //
  141. // The fetcher avoids caching. That is best for API requests, but may hurt
  142. // repeat fetches of static data. Apps may enable a persistent disk cache by
  143. // customizing the config:
  144. //
  145. // fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher,
  146. // NSURLSessionConfiguration *config) {
  147. // config.URLCache = [NSURLCache sharedURLCache];
  148. // };
  149. //
  150. // Or use the standard system config to share cookie storage with web views
  151. // and to enable disk caching:
  152. //
  153. // fetcher.configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  154. //
  155. //
  156. // Cookies:
  157. //
  158. // There are three supported mechanisms for remembering cookies between fetches.
  159. //
  160. // By default, a standalone GTMSessionFetcher uses a mutable array held
  161. // statically to track cookies for all instantiated fetchers. This avoids
  162. // cookies being set by servers for the application from interfering with
  163. // Safari and WebKit cookie settings, and vice versa.
  164. // The fetcher cookies are lost when the application quits.
  165. //
  166. // To rely instead on WebKit's global NSHTTPCookieStorage, set the fetcher's
  167. // cookieStorage property:
  168. // myFetcher.cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  169. //
  170. // To share cookies with other apps, use the method introduced in iOS 9/OS X 10.11:
  171. // myFetcher.cookieStorage =
  172. // [NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:kMyCompanyContainedID];
  173. //
  174. // To ignore existing cookies and only have cookies related to the single fetch
  175. // be applied, make a temporary cookie storage object:
  176. // myFetcher.cookieStorage = [[GTMSessionCookieStorage alloc] init];
  177. //
  178. // Note: cookies set while following redirects will be sent to the server, as
  179. // the redirects are followed by the fetcher.
  180. //
  181. // To completely disable cookies, similar to setting cookieStorageMethod to
  182. // kGTMHTTPFetcherCookieStorageMethodNone, adjust the session configuration
  183. // appropriately in the fetcher or fetcher service:
  184. // fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher,
  185. // NSURLSessionConfiguration *config) {
  186. // config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
  187. // config.HTTPShouldSetCookies = NO;
  188. // };
  189. //
  190. // If the fetcher is created from a GTMSessionFetcherService object
  191. // then the cookie storage mechanism is set to use the cookie storage in the
  192. // service object rather than the static storage. Disabling cookies in the
  193. // session configuration set on a service object will disable cookies for all
  194. // fetchers created from that GTMSessionFetcherService object, since the session
  195. // configuration is propagated to the fetcher.
  196. //
  197. //
  198. // Monitoring data transfers.
  199. //
  200. // The fetcher supports a variety of properties for progress monitoring
  201. // progress with callback blocks.
  202. // GTMSessionFetcherSendProgressBlock sendProgressBlock
  203. // GTMSessionFetcherReceivedProgressBlock receivedProgressBlock
  204. // GTMSessionFetcherDownloadProgressBlock downloadProgressBlock
  205. //
  206. // If supplied by the server, the anticipated total download size is available
  207. // as [[myFetcher response] expectedContentLength] (and may be -1 for unknown
  208. // download sizes.)
  209. //
  210. //
  211. // Automatic retrying of fetches
  212. //
  213. // The fetcher can optionally create a timer and reattempt certain kinds of
  214. // fetch failures (status codes 408, request timeout; 502, gateway failure;
  215. // 503, service unavailable; 504, gateway timeout; networking errors
  216. // NSURLErrorTimedOut and NSURLErrorNetworkConnectionLost.) The user may
  217. // set a retry selector to customize the type of errors which will be retried.
  218. //
  219. // Retries are done in an exponential-backoff fashion (that is, after 1 second,
  220. // 2, 4, 8, and so on.)
  221. //
  222. // Enabling automatic retries looks like this:
  223. // myFetcher.retryEnabled = YES;
  224. //
  225. // With retries enabled, the completion callbacks are called only
  226. // when no more retries will be attempted. Calling the fetcher's stopFetching
  227. // method will terminate the retry timer, without the finished or failure
  228. // selectors being invoked.
  229. //
  230. // Optionally, the client may set the maximum retry interval:
  231. // myFetcher.maxRetryInterval = 60.0; // in seconds; default is 60 seconds
  232. // // for downloads, 600 for uploads
  233. //
  234. // Servers should never send a 400 or 500 status for errors that are retryable
  235. // by clients, as those values indicate permanent failures. In nearly all
  236. // cases, the default standard retry behavior is correct for clients, and no
  237. // custom client retry behavior is needed or appropriate. Servers that send
  238. // non-retryable status codes and expect the client to retry the request are
  239. // faulty.
  240. //
  241. // Still, the client may provide a block to determine if a status code or other
  242. // error should be retried. The block returns YES to set the retry timer or NO
  243. // to fail without additional fetch attempts.
  244. //
  245. // The retry method may return the |suggestedWillRetry| argument to get the
  246. // default retry behavior. Server status codes are present in the
  247. // error argument, and have the domain kGTMSessionFetcherStatusDomain. The
  248. // user's method may look something like this:
  249. //
  250. // myFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error,
  251. // GTMSessionFetcherRetryResponse response) {
  252. // // Perhaps examine error.domain and error.code, or fetcher.retryCount
  253. // //
  254. // // Respond with YES to start the retry timer, NO to proceed to the failure
  255. // // callback, or suggestedWillRetry to get default behavior for the
  256. // // current error domain and code values.
  257. // response(suggestedWillRetry);
  258. // };
  259. #import <Foundation/Foundation.h>
  260. #if TARGET_OS_IPHONE
  261. #import <UIKit/UIKit.h>
  262. #endif
  263. #if TARGET_OS_WATCH
  264. #import <WatchKit/WatchKit.h>
  265. #endif
  266. // By default it is stripped from non DEBUG builds. Developers can override
  267. // this in their project settings.
  268. #ifndef STRIP_GTM_FETCH_LOGGING
  269. #if !DEBUG
  270. #define STRIP_GTM_FETCH_LOGGING 1
  271. #else
  272. #define STRIP_GTM_FETCH_LOGGING 0
  273. #endif
  274. #endif
  275. // Logs in debug builds.
  276. #ifndef GTMSESSION_LOG_DEBUG
  277. #if DEBUG
  278. #define GTMSESSION_LOG_DEBUG(...) NSLog(__VA_ARGS__)
  279. #else
  280. #define GTMSESSION_LOG_DEBUG(...) do { } while (0)
  281. #endif
  282. #endif
  283. // Asserts in debug builds (or logs in debug builds if GTMSESSION_ASSERT_AS_LOG
  284. // or NS_BLOCK_ASSERTIONS are defined.)
  285. #ifndef GTMSESSION_ASSERT_DEBUG
  286. #if DEBUG && !defined(NS_BLOCK_ASSERTIONS) && !GTMSESSION_ASSERT_AS_LOG
  287. #undef GTMSESSION_ASSERT_AS_LOG
  288. #define GTMSESSION_ASSERT_AS_LOG 1
  289. #endif
  290. #if DEBUG && !GTMSESSION_ASSERT_AS_LOG
  291. #define GTMSESSION_ASSERT_DEBUG(...) NSAssert(__VA_ARGS__)
  292. #elif DEBUG
  293. #define GTMSESSION_ASSERT_DEBUG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); }
  294. #else
  295. #define GTMSESSION_ASSERT_DEBUG(pred, ...) do { } while (0)
  296. #endif
  297. #endif
  298. // Asserts in debug builds, logs in release builds (or logs in debug builds if
  299. // GTMSESSION_ASSERT_AS_LOG is defined.)
  300. #ifndef GTMSESSION_ASSERT_DEBUG_OR_LOG
  301. #if DEBUG && !GTMSESSION_ASSERT_AS_LOG
  302. #define GTMSESSION_ASSERT_DEBUG_OR_LOG(...) NSAssert(__VA_ARGS__)
  303. #else
  304. #define GTMSESSION_ASSERT_DEBUG_OR_LOG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); }
  305. #endif
  306. #endif
  307. // Macro useful for examining messages from NSURLSession during debugging.
  308. #if 0
  309. #define GTM_LOG_SESSION_DELEGATE(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__)
  310. #else
  311. #define GTM_LOG_SESSION_DELEGATE(...)
  312. #endif
  313. #ifndef GTM_NULLABLE
  314. #if __has_feature(nullability) // Available starting in Xcode 6.3
  315. #define GTM_NULLABLE_TYPE __nullable
  316. #define GTM_NONNULL_TYPE __nonnull
  317. #define GTM_NULLABLE nullable
  318. #define GTM_NONNULL_DECL nonnull // GTM_NONNULL is used by GTMDefines.h
  319. #define GTM_NULL_RESETTABLE null_resettable
  320. #define GTM_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
  321. #define GTM_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
  322. #else
  323. #define GTM_NULLABLE_TYPE
  324. #define GTM_NONNULL_TYPE
  325. #define GTM_NULLABLE
  326. #define GTM_NONNULL_DECL
  327. #define GTM_NULL_RESETTABLE
  328. #define GTM_ASSUME_NONNULL_BEGIN
  329. #define GTM_ASSUME_NONNULL_END
  330. #endif // __has_feature(nullability)
  331. #endif // GTM_NULLABLE
  332. #if (TARGET_OS_TV \
  333. || TARGET_OS_WATCH \
  334. || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12) \
  335. || (TARGET_OS_IPHONE && defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0))
  336. #define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) __attribute__((deprecated("" _MSG)))
  337. #else
  338. #define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG)
  339. #endif
  340. #ifndef GTM_DECLARE_GENERICS
  341. #if __has_feature(objc_generics)
  342. #define GTM_DECLARE_GENERICS 1
  343. #else
  344. #define GTM_DECLARE_GENERICS 0
  345. #endif
  346. #endif
  347. #ifndef GTM_NSArrayOf
  348. #if GTM_DECLARE_GENERICS
  349. #define GTM_NSArrayOf(value) NSArray<value>
  350. #define GTM_NSDictionaryOf(key, value) NSDictionary<key, value>
  351. #else
  352. #define GTM_NSArrayOf(value) NSArray
  353. #define GTM_NSDictionaryOf(key, value) NSDictionary
  354. #endif // __has_feature(objc_generics)
  355. #endif // GTM_NSArrayOf
  356. // For iOS, the fetcher can declare itself a background task to allow fetches
  357. // to finish when the app leaves the foreground.
  358. //
  359. // (This is unrelated to providing a background configuration, which allows
  360. // out-of-process uploads and downloads.)
  361. //
  362. // To disallow use of background tasks during fetches, the target should define
  363. // GTM_BACKGROUND_TASK_FETCHING to 0, or alternatively may set the
  364. // skipBackgroundTask property to YES.
  365. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH && !defined(GTM_BACKGROUND_TASK_FETCHING)
  366. #define GTM_BACKGROUND_TASK_FETCHING 1
  367. #endif
  368. #ifdef __cplusplus
  369. extern "C" {
  370. #endif
  371. #if (TARGET_OS_TV \
  372. || TARGET_OS_WATCH \
  373. || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \
  374. || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0))
  375. #ifndef GTM_USE_SESSION_FETCHER
  376. #define GTM_USE_SESSION_FETCHER 1
  377. #endif
  378. #endif
  379. #if !defined(GTMBridgeFetcher)
  380. // These bridge macros should be identical in GTMHTTPFetcher.h and GTMSessionFetcher.h
  381. #if GTM_USE_SESSION_FETCHER
  382. // Macros to new fetcher class.
  383. #define GTMBridgeFetcher GTMSessionFetcher
  384. #define GTMBridgeFetcherService GTMSessionFetcherService
  385. #define GTMBridgeFetcherServiceProtocol GTMSessionFetcherServiceProtocol
  386. #define GTMBridgeAssertValidSelector GTMSessionFetcherAssertValidSelector
  387. #define GTMBridgeCookieStorage GTMSessionCookieStorage
  388. #define GTMBridgeCleanedUserAgentString GTMFetcherCleanedUserAgentString
  389. #define GTMBridgeSystemVersionString GTMFetcherSystemVersionString
  390. #define GTMBridgeApplicationIdentifier GTMFetcherApplicationIdentifier
  391. #define kGTMBridgeFetcherStatusDomain kGTMSessionFetcherStatusDomain
  392. #define kGTMBridgeFetcherStatusBadRequest GTMSessionFetcherStatusBadRequest
  393. #else
  394. // Macros to old fetcher class.
  395. #define GTMBridgeFetcher GTMHTTPFetcher
  396. #define GTMBridgeFetcherService GTMHTTPFetcherService
  397. #define GTMBridgeFetcherServiceProtocol GTMHTTPFetcherServiceProtocol
  398. #define GTMBridgeAssertValidSelector GTMAssertSelectorNilOrImplementedWithArgs
  399. #define GTMBridgeCookieStorage GTMCookieStorage
  400. #define GTMBridgeCleanedUserAgentString GTMCleanedUserAgentString
  401. #define GTMBridgeSystemVersionString GTMSystemVersionString
  402. #define GTMBridgeApplicationIdentifier GTMApplicationIdentifier
  403. #define kGTMBridgeFetcherStatusDomain kGTMHTTPFetcherStatusDomain
  404. #define kGTMBridgeFetcherStatusBadRequest kGTMHTTPFetcherStatusBadRequest
  405. #endif // GTM_USE_SESSION_FETCHER
  406. #endif
  407. // When creating background sessions to perform out-of-process uploads and
  408. // downloads, on app launch any background sessions must be reconnected in
  409. // order to receive events that occurred while the app was not running.
  410. //
  411. // The fetcher will automatically attempt to recreate the sessions on app
  412. // start, but doing so reads from NSUserDefaults. This may have launch-time
  413. // performance impacts.
  414. //
  415. // To avoid launch performance impacts, on iPhone/iPad with iOS 13+ the
  416. // GTMSessionFetcher class will register for the app launch notification and
  417. // perform the reconnect then.
  418. //
  419. // Apps targeting Mac or older iOS SDKs can opt into the new behavior by defining
  420. // GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH=1.
  421. //
  422. // Apps targeting new SDKs can force the old behavior by defining
  423. // GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH = 0.
  424. #ifndef GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH
  425. // Default to the on-launch behavior for iOS 13+.
  426. #if TARGET_OS_IOS && defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  427. #define GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH 1
  428. #else
  429. #define GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH 0
  430. #endif
  431. #endif
  432. GTM_ASSUME_NONNULL_BEGIN
  433. // Notifications
  434. //
  435. // Fetch started and stopped, and fetch retry delay started and stopped.
  436. extern NSString *const kGTMSessionFetcherStartedNotification;
  437. extern NSString *const kGTMSessionFetcherStoppedNotification;
  438. extern NSString *const kGTMSessionFetcherRetryDelayStartedNotification;
  439. extern NSString *const kGTMSessionFetcherRetryDelayStoppedNotification;
  440. // Completion handler notification. This is intended for use by code capturing
  441. // and replaying fetch requests and results for testing. For fetches where
  442. // destinationFileURL or accumulateDataBlock is set for the fetcher, the data
  443. // will be nil for successful fetches.
  444. //
  445. // This notification is posted on the main thread.
  446. extern NSString *const kGTMSessionFetcherCompletionInvokedNotification;
  447. extern NSString *const kGTMSessionFetcherCompletionDataKey;
  448. extern NSString *const kGTMSessionFetcherCompletionErrorKey;
  449. // Constants for NSErrors created by the fetcher (excluding server status errors,
  450. // and error objects originating in the OS.)
  451. extern NSString *const kGTMSessionFetcherErrorDomain;
  452. // The fetcher turns server error status values (3XX, 4XX, 5XX) into NSErrors
  453. // with domain kGTMSessionFetcherStatusDomain.
  454. //
  455. // Any server response body data accompanying the status error is added to the
  456. // userInfo dictionary with key kGTMSessionFetcherStatusDataKey.
  457. extern NSString *const kGTMSessionFetcherStatusDomain;
  458. extern NSString *const kGTMSessionFetcherStatusDataKey;
  459. extern NSString *const kGTMSessionFetcherStatusDataContentTypeKey;
  460. // When a fetch fails with an error, these keys are included in the error userInfo
  461. // dictionary if retries were attempted.
  462. extern NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey;
  463. extern NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey;
  464. // Background session support requires access to NSUserDefaults.
  465. // If [NSUserDefaults standardUserDefaults] doesn't yield the correct NSUserDefaults for your usage,
  466. // ie for an App Extension, then implement this class/method to return the correct NSUserDefaults.
  467. // https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6
  468. @interface GTMSessionFetcherUserDefaultsFactory : NSObject
  469. + (NSUserDefaults *)fetcherUserDefaults;
  470. @end
  471. #ifdef __cplusplus
  472. }
  473. #endif
  474. typedef NS_ENUM(NSInteger, GTMSessionFetcherError) {
  475. GTMSessionFetcherErrorDownloadFailed = -1,
  476. GTMSessionFetcherErrorUploadChunkUnavailable = -2,
  477. GTMSessionFetcherErrorBackgroundExpiration = -3,
  478. GTMSessionFetcherErrorBackgroundFetchFailed = -4,
  479. GTMSessionFetcherErrorInsecureRequest = -5,
  480. GTMSessionFetcherErrorTaskCreationFailed = -6,
  481. };
  482. typedef NS_ENUM(NSInteger, GTMSessionFetcherStatus) {
  483. // Standard http status codes.
  484. GTMSessionFetcherStatusNotModified = 304,
  485. GTMSessionFetcherStatusBadRequest = 400,
  486. GTMSessionFetcherStatusUnauthorized = 401,
  487. GTMSessionFetcherStatusForbidden = 403,
  488. GTMSessionFetcherStatusPreconditionFailed = 412
  489. };
  490. #ifdef __cplusplus
  491. extern "C" {
  492. #endif
  493. @class GTMSessionCookieStorage;
  494. @class GTMSessionFetcher;
  495. // The configuration block is for modifying the NSURLSessionConfiguration only.
  496. // DO NOT change any fetcher properties in the configuration block.
  497. typedef void (^GTMSessionFetcherConfigurationBlock)(GTMSessionFetcher *fetcher,
  498. NSURLSessionConfiguration *configuration);
  499. typedef void (^GTMSessionFetcherSystemCompletionHandler)(void);
  500. typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data,
  501. NSError * GTM_NULLABLE_TYPE error);
  502. typedef void (^GTMSessionFetcherBodyStreamProviderResponse)(NSInputStream *bodyStream);
  503. typedef void (^GTMSessionFetcherBodyStreamProvider)(GTMSessionFetcherBodyStreamProviderResponse response);
  504. typedef void (^GTMSessionFetcherDidReceiveResponseDispositionBlock)(NSURLSessionResponseDisposition disposition);
  505. typedef void (^GTMSessionFetcherDidReceiveResponseBlock)(NSURLResponse *response,
  506. GTMSessionFetcherDidReceiveResponseDispositionBlock dispositionBlock);
  507. typedef void (^GTMSessionFetcherChallengeDispositionBlock)(NSURLSessionAuthChallengeDisposition disposition,
  508. NSURLCredential * GTM_NULLABLE_TYPE credential);
  509. typedef void (^GTMSessionFetcherChallengeBlock)(GTMSessionFetcher *fetcher,
  510. NSURLAuthenticationChallenge *challenge,
  511. GTMSessionFetcherChallengeDispositionBlock dispositionBlock);
  512. typedef void (^GTMSessionFetcherWillRedirectResponse)(NSURLRequest * GTM_NULLABLE_TYPE redirectedRequest);
  513. typedef void (^GTMSessionFetcherWillRedirectBlock)(NSHTTPURLResponse *redirectResponse,
  514. NSURLRequest *redirectRequest,
  515. GTMSessionFetcherWillRedirectResponse response);
  516. typedef void (^GTMSessionFetcherAccumulateDataBlock)(NSData * GTM_NULLABLE_TYPE buffer);
  517. typedef void (^GTMSessionFetcherSimulateByteTransferBlock)(NSData * GTM_NULLABLE_TYPE buffer,
  518. int64_t bytesWritten,
  519. int64_t totalBytesWritten,
  520. int64_t totalBytesExpectedToWrite);
  521. typedef void (^GTMSessionFetcherReceivedProgressBlock)(int64_t bytesWritten,
  522. int64_t totalBytesWritten);
  523. typedef void (^GTMSessionFetcherDownloadProgressBlock)(int64_t bytesWritten,
  524. int64_t totalBytesWritten,
  525. int64_t totalBytesExpectedToWrite);
  526. typedef void (^GTMSessionFetcherSendProgressBlock)(int64_t bytesSent,
  527. int64_t totalBytesSent,
  528. int64_t totalBytesExpectedToSend);
  529. typedef void (^GTMSessionFetcherWillCacheURLResponseResponse)(NSCachedURLResponse * GTM_NULLABLE_TYPE cachedResponse);
  530. typedef void (^GTMSessionFetcherWillCacheURLResponseBlock)(NSCachedURLResponse *proposedResponse,
  531. GTMSessionFetcherWillCacheURLResponseResponse responseBlock);
  532. typedef void (^GTMSessionFetcherRetryResponse)(BOOL shouldRetry);
  533. typedef void (^GTMSessionFetcherRetryBlock)(BOOL suggestedWillRetry,
  534. NSError * GTM_NULLABLE_TYPE error,
  535. GTMSessionFetcherRetryResponse response);
  536. typedef void (^GTMSessionFetcherTestResponse)(NSHTTPURLResponse * GTM_NULLABLE_TYPE response,
  537. NSData * GTM_NULLABLE_TYPE data,
  538. NSError * GTM_NULLABLE_TYPE error);
  539. typedef void (^GTMSessionFetcherTestBlock)(GTMSessionFetcher *fetcherToTest,
  540. GTMSessionFetcherTestResponse testResponse);
  541. void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...);
  542. // Utility functions for applications self-identifying to servers via a
  543. // user-agent header
  544. // The "standard" user agent includes the application identifier, taken from the bundle,
  545. // followed by a space and the system version string. Pass nil to use +mainBundle as the source
  546. // of the bundle identifier.
  547. //
  548. // Applications may use this as a starting point for their own user agent strings, perhaps
  549. // with additional sections appended. Use GTMFetcherCleanedUserAgentString() below to
  550. // clean up any string being added to the user agent.
  551. NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle);
  552. // Make a generic name and version for the current application, like
  553. // com.example.MyApp/1.2.3 relying on the bundle identifier and the
  554. // CFBundleShortVersionString or CFBundleVersion.
  555. //
  556. // The bundle ID may be overridden as the base identifier string by
  557. // adding to the bundle's Info.plist a "GTMUserAgentID" key.
  558. //
  559. // If no bundle ID or override is available, the process name preceded
  560. // by "proc_" is used.
  561. NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle);
  562. // Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1"
  563. NSString *GTMFetcherSystemVersionString(void);
  564. // Make a parseable user-agent identifier from the given string, replacing whitespace
  565. // and commas with underscores, and removing other characters that may interfere
  566. // with parsing of the full user-agent string.
  567. //
  568. // For example, @"[My App]" would become @"My_App"
  569. NSString *GTMFetcherCleanedUserAgentString(NSString *str);
  570. // Grab the data from an input stream. Since streams cannot be assumed to be rewindable,
  571. // this may be destructive; the caller can try to rewind the stream (by setting the
  572. // NSStreamFileCurrentOffsetKey property) or can just use the NSData to make a new
  573. // NSInputStream. This function is intended to facilitate testing rather than be used in
  574. // production.
  575. //
  576. // This function operates synchronously on the current thread. Depending on how the
  577. // input stream is implemented, it may be appropriate to dispatch to a different
  578. // queue before calling this function.
  579. //
  580. // Failure is indicated by a returned data value of nil.
  581. NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError);
  582. #ifdef __cplusplus
  583. } // extern "C"
  584. #endif
  585. #if !GTM_USE_SESSION_FETCHER
  586. @protocol GTMHTTPFetcherServiceProtocol;
  587. #endif
  588. // This protocol allows abstract references to the fetcher service, primarily for
  589. // fetchers (which may be compiled without the fetcher service class present.)
  590. //
  591. // Apps should not need to use this protocol.
  592. @protocol GTMSessionFetcherServiceProtocol <NSObject>
  593. // This protocol allows us to call into the service without requiring
  594. // GTMSessionFetcherService sources in this project
  595. @property(atomic, strong) dispatch_queue_t callbackQueue;
  596. - (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher;
  597. - (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher;
  598. - (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher;
  599. - (void)fetcherDidStop:(GTMSessionFetcher *)fetcher;
  600. - (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request;
  601. - (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher;
  602. @property(atomic, assign) BOOL reuseSession;
  603. - (GTM_NULLABLE NSURLSession *)session;
  604. - (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation;
  605. - (GTM_NULLABLE id<NSURLSessionDelegate>)sessionDelegate;
  606. - (GTM_NULLABLE NSDate *)stoppedAllFetchersDate;
  607. // Methods for compatibility with the old GTMHTTPFetcher.
  608. @property(atomic, readonly, strong, GTM_NULLABLE) NSOperationQueue *delegateQueue;
  609. @end // @protocol GTMSessionFetcherServiceProtocol
  610. #ifndef GTM_FETCHER_AUTHORIZATION_PROTOCOL
  611. #define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1
  612. @protocol GTMFetcherAuthorizationProtocol <NSObject>
  613. @required
  614. // This protocol allows us to call the authorizer without requiring its sources
  615. // in this project.
  616. - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request
  617. delegate:(id)delegate
  618. didFinishSelector:(SEL)sel;
  619. - (void)stopAuthorization;
  620. - (void)stopAuthorizationForRequest:(NSURLRequest *)request;
  621. - (BOOL)isAuthorizingRequest:(NSURLRequest *)request;
  622. - (BOOL)isAuthorizedRequest:(NSURLRequest *)request;
  623. @property(atomic, strong, readonly, GTM_NULLABLE) NSString *userEmail;
  624. @optional
  625. // Indicate if authorization may be attempted. Even if this succeeds,
  626. // authorization may fail if the user's permissions have been revoked.
  627. @property(atomic, readonly) BOOL canAuthorize;
  628. // For development only, allow authorization of non-SSL requests, allowing
  629. // transmission of the bearer token unencrypted.
  630. @property(atomic, assign) BOOL shouldAuthorizeAllRequests;
  631. - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request
  632. completionHandler:(void (^)(NSError * GTM_NULLABLE_TYPE error))handler;
  633. #if GTM_USE_SESSION_FETCHER
  634. @property(atomic, weak, GTM_NULLABLE) id<GTMSessionFetcherServiceProtocol> fetcherService;
  635. #else
  636. @property(atomic, weak, GTM_NULLABLE) id<GTMHTTPFetcherServiceProtocol> fetcherService;
  637. #endif
  638. - (BOOL)primeForRefresh;
  639. @end
  640. #endif // GTM_FETCHER_AUTHORIZATION_PROTOCOL
  641. #if GTM_BACKGROUND_TASK_FETCHING
  642. // A protocol for an alternative target for messages from GTMSessionFetcher to UIApplication.
  643. // Set the target using +[GTMSessionFetcher setSubstituteUIApplication:]
  644. @protocol GTMUIApplicationProtocol <NSObject>
  645. - (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName
  646. expirationHandler:(void(^ __nullable)(void))handler;
  647. - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier;
  648. @end
  649. #endif
  650. #pragma mark -
  651. // GTMSessionFetcher objects are used for async retrieval of an http get or post
  652. //
  653. // See additional comments at the beginning of this file
  654. @interface GTMSessionFetcher : NSObject <NSURLSessionDelegate>
  655. // Create a fetcher
  656. //
  657. // fetcherWithRequest will return an autoreleased fetcher, but if
  658. // the connection is successfully created, the connection should retain the
  659. // fetcher for the life of the connection as well. So the caller doesn't have
  660. // to retain the fetcher explicitly unless they want to be able to cancel it.
  661. + (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request;
  662. // Convenience methods that make a request, like +fetcherWithRequest
  663. + (instancetype)fetcherWithURL:(NSURL *)requestURL;
  664. + (instancetype)fetcherWithURLString:(NSString *)requestURLString;
  665. // Methods for creating fetchers to continue previous fetches.
  666. + (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData;
  667. + (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier;
  668. // Returns an array of currently active fetchers for background sessions,
  669. // both restarted and newly created ones.
  670. + (GTM_NSArrayOf(GTMSessionFetcher *) *)fetchersForBackgroundSessions;
  671. // Designated initializer.
  672. //
  673. // Applications should create fetchers with a "fetcherWith..." method on a fetcher
  674. // service or a class method, not with this initializer.
  675. //
  676. // The configuration should typically be nil. Applications needing to customize
  677. // the configuration may do so by setting the configurationBlock property.
  678. - (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request
  679. configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration;
  680. // The fetcher's request. This may not be set after beginFetch has been invoked. The request
  681. // may change due to redirects.
  682. @property(atomic, strong, GTM_NULLABLE) NSURLRequest *request;
  683. // Set a header field value on the request. Header field value changes will not
  684. // affect a fetch after the fetch has begun.
  685. - (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field;
  686. // Data used for resuming a download task.
  687. @property(atomic, readonly, GTM_NULLABLE) NSData *downloadResumeData;
  688. // The configuration; this must be set before the fetch begins. If no configuration is
  689. // set or inherited from the fetcher service, then the fetcher uses an ephemeral config.
  690. //
  691. // NOTE: This property should typically be nil. Applications needing to customize
  692. // the configuration should do so by setting the configurationBlock property.
  693. // That allows the fetcher to pick an appropriate base configuration, with the
  694. // application setting only the configuration properties it needs to customize.
  695. @property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration;
  696. // A block the client may use to customize the configuration used to create the session.
  697. //
  698. // This is called synchronously, either on the thread that begins the fetch or, during a retry,
  699. // on the main thread. The configuration block may be called repeatedly if multiple fetchers are
  700. // created.
  701. //
  702. // The configuration block is for modifying the NSURLSessionConfiguration only.
  703. // DO NOT change any fetcher properties in the configuration block. Fetcher properties
  704. // may be set in the fetcher service prior to fetcher creation, or on the fetcher prior
  705. // to invoking beginFetch.
  706. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock;
  707. // A session is created as needed by the fetcher. A fetcher service object
  708. // may maintain sessions for multiple fetches to the same host.
  709. @property(atomic, strong, GTM_NULLABLE) NSURLSession *session;
  710. // The task in flight.
  711. @property(atomic, readonly, GTM_NULLABLE) NSURLSessionTask *sessionTask;
  712. // The background session identifier.
  713. @property(atomic, readonly, GTM_NULLABLE) NSString *sessionIdentifier;
  714. // Indicates a fetcher created to finish a background session task.
  715. @property(atomic, readonly) BOOL wasCreatedFromBackgroundSession;
  716. // Additional user-supplied data to encode into the session identifier. Since session identifier
  717. // length limits are unspecified, this should be kept small. Key names beginning with an underscore
  718. // are reserved for use by the fetcher.
  719. @property(atomic, strong, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *sessionUserInfo;
  720. // The human-readable description to be assigned to the task.
  721. @property(atomic, copy, GTM_NULLABLE) NSString *taskDescription;
  722. // The priority assigned to the task, if any. Use NSURLSessionTaskPriorityLow,
  723. // NSURLSessionTaskPriorityDefault, or NSURLSessionTaskPriorityHigh.
  724. @property(atomic, assign) float taskPriority;
  725. // The fetcher encodes information used to resume a session in the session identifier.
  726. // This method, intended for internal use returns the encoded information. The sessionUserInfo
  727. // dictionary is stored as identifier metadata.
  728. - (GTM_NULLABLE GTM_NSDictionaryOf(NSString *, NSString *) *)sessionIdentifierMetadata;
  729. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH
  730. // The app should pass to this method the completion handler passed in the app delegate method
  731. // application:handleEventsForBackgroundURLSession:completionHandler:
  732. + (void)application:(UIApplication *)application
  733. handleEventsForBackgroundURLSession:(NSString *)identifier
  734. completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler;
  735. #endif
  736. // Indicate that a newly created session should be a background session.
  737. // A new session identifier will be created by the fetcher.
  738. //
  739. // Warning: The only thing background sessions are for is rare download
  740. // of huge, batched files of data. And even just for those, there's a lot
  741. // of pain and hackery needed to get transfers to actually happen reliably
  742. // with background sessions.
  743. //
  744. // Don't try to upload or download in many background sessions, since the system
  745. // will impose an exponentially increasing time penalty to prevent the app from
  746. // getting too much background execution time.
  747. //
  748. // References:
  749. //
  750. // "Moving to Fewer, Larger Transfers"
  751. // https://forums.developer.apple.com/thread/14853
  752. //
  753. // "NSURLSession’s Resume Rate Limiter"
  754. // https://forums.developer.apple.com/thread/14854
  755. //
  756. // "Background Session Task state persistence"
  757. // https://forums.developer.apple.com/thread/11554
  758. //
  759. @property(atomic, assign) BOOL useBackgroundSession;
  760. // Indicates if the fetcher was started using a background session.
  761. @property(atomic, readonly, getter=isUsingBackgroundSession) BOOL usingBackgroundSession;
  762. // Indicates if uploads should use an upload task. This is always set for file or stream-provider
  763. // bodies, but may be set explicitly for NSData bodies.
  764. @property(atomic, assign) BOOL useUploadTask;
  765. // Indicates that the fetcher is using a session that may be shared with other fetchers.
  766. @property(atomic, readonly) BOOL canShareSession;
  767. // By default, the fetcher allows only secure (https) schemes unless this
  768. // property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set.
  769. //
  770. // For example, during debugging when fetching from a development server that lacks SSL support,
  771. // this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files,
  772. // this may be set to @[ @"file" ].
  773. //
  774. // This should be left as nil for release builds to avoid creating the opportunity for
  775. // leaking private user behavior and data. If a server is providing insecure URLs
  776. // for fetching by the client app, report the problem as server security & privacy bug.
  777. //
  778. // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when
  779. // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist.
  780. @property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes;
  781. // By default, the fetcher prohibits localhost requests unless this property is set,
  782. // or the GTM_ALLOW_INSECURE_REQUESTS build flag is set.
  783. //
  784. // For localhost requests, the URL scheme is not checked when this property is set.
  785. //
  786. // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when
  787. // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist.
  788. @property(atomic, assign) BOOL allowLocalhostRequest;
  789. // By default, the fetcher requires valid server certs. This may be bypassed
  790. // temporarily for development against a test server with an invalid cert.
  791. @property(atomic, assign) BOOL allowInvalidServerCertificates;
  792. // Cookie storage object for this fetcher. If nil, the fetcher will use a static cookie
  793. // storage instance shared among fetchers. If this fetcher was created by a fetcher service
  794. // object, it will be set to use the service object's cookie storage. See Cookies section above for
  795. // the full discussion.
  796. //
  797. // Because as of Jan 2014 standalone instances of NSHTTPCookieStorage do not actually
  798. // store any cookies (Radar 15735276) we use our own subclass, GTMSessionCookieStorage,
  799. // to hold cookies in memory.
  800. @property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage;
  801. // Setting the credential is optional; it is used if the connection receives
  802. // an authentication challenge.
  803. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential;
  804. // Setting the proxy credential is optional; it is used if the connection
  805. // receives an authentication challenge from a proxy.
  806. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *proxyCredential;
  807. // If body data, body file URL, or body stream provider is not set, then a GET request
  808. // method is assumed.
  809. @property(atomic, strong, GTM_NULLABLE) NSData *bodyData;
  810. // File to use as the request body. This forces use of an upload task.
  811. @property(atomic, strong, GTM_NULLABLE) NSURL *bodyFileURL;
  812. // Length of body to send, expected or actual.
  813. @property(atomic, readonly) int64_t bodyLength;
  814. // The body stream provider may be called repeatedly to provide a body.
  815. // Setting a body stream provider forces use of an upload task.
  816. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherBodyStreamProvider bodyStreamProvider;
  817. // Object to add authorization to the request, if needed.
  818. //
  819. // This may not be changed once beginFetch has been invoked.
  820. @property(atomic, strong, GTM_NULLABLE) id<GTMFetcherAuthorizationProtocol> authorizer;
  821. // The service object that created and monitors this fetcher, if any.
  822. @property(atomic, strong) id<GTMSessionFetcherServiceProtocol> service;
  823. // The host, if any, used to classify this fetcher in the fetcher service.
  824. @property(atomic, copy, GTM_NULLABLE) NSString *serviceHost;
  825. // The priority, if any, used for starting fetchers in the fetcher service.
  826. //
  827. // Lower values are higher priority; the default is 0, and values may
  828. // be negative or positive. This priority affects only the start order of
  829. // fetchers that are being delayed by a fetcher service when the running fetchers
  830. // exceeds the service's maxRunningFetchersPerHost. A priority of NSIntegerMin will
  831. // exempt this fetcher from delay.
  832. @property(atomic, assign) NSInteger servicePriority;
  833. // The delegate's optional didReceiveResponse block may be used to inspect or alter
  834. // the session task response.
  835. //
  836. // This is called on the callback queue.
  837. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock;
  838. // The delegate's optional challenge block may be used to inspect or alter
  839. // the session task challenge.
  840. //
  841. // If this block is not set, the fetcher's default behavior for the NSURLSessionTask
  842. // didReceiveChallenge: delegate method is to use the fetcher's respondToChallenge: method
  843. // which relies on the fetcher's credential and proxyCredential properties.
  844. //
  845. // Warning: This may be called repeatedly if the challenge fails. Check
  846. // challenge.previousFailureCount to identify repeated invocations.
  847. //
  848. // This is called on the callback queue.
  849. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock;
  850. // The delegate's optional willRedirect block may be used to inspect or alter
  851. // the redirection.
  852. //
  853. // This is called on the callback queue.
  854. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillRedirectBlock willRedirectBlock;
  855. // The optional send progress block reports body bytes uploaded.
  856. //
  857. // This is called on the callback queue.
  858. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherSendProgressBlock sendProgressBlock;
  859. // The optional accumulate block may be set by clients wishing to accumulate data
  860. // themselves rather than let the fetcher append each buffer to an NSData.
  861. //
  862. // When this is called with nil data (such as on redirect) the client
  863. // should empty its accumulation buffer.
  864. //
  865. // This is called on the callback queue.
  866. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherAccumulateDataBlock accumulateDataBlock;
  867. // The optional received progress block may be used to monitor data
  868. // received from a data task.
  869. //
  870. // This is called on the callback queue.
  871. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherReceivedProgressBlock receivedProgressBlock;
  872. // The delegate's optional downloadProgress block may be used to monitor download
  873. // progress in writing to disk.
  874. //
  875. // This is called on the callback queue.
  876. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDownloadProgressBlock downloadProgressBlock;
  877. // The delegate's optional willCacheURLResponse block may be used to alter the cached
  878. // NSURLResponse. The user may prevent caching by passing nil to the block's response.
  879. //
  880. // This is called on the callback queue.
  881. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock;
  882. // Enable retrying; see comments at the top of this file. Setting
  883. // retryEnabled=YES resets the min and max retry intervals.
  884. @property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled;
  885. // Retry block is optional for retries.
  886. //
  887. // If present, this block should call the response block with YES to cause a retry or NO to end the
  888. // fetch.
  889. // See comments at the top of this file.
  890. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock;
  891. // Retry intervals must be strictly less than maxRetryInterval, else
  892. // they will be limited to maxRetryInterval and no further retries will
  893. // be attempted. Setting maxRetryInterval to 0.0 will reset it to the
  894. // default value, 60 seconds for downloads and 600 seconds for uploads.
  895. @property(atomic, assign) NSTimeInterval maxRetryInterval;
  896. // Starting retry interval. Setting minRetryInterval to 0.0 will reset it
  897. // to a random value between 1.0 and 2.0 seconds. Clients should normally not
  898. // set this except for unit testing.
  899. @property(atomic, assign) NSTimeInterval minRetryInterval;
  900. // Multiplier used to increase the interval between retries, typically 2.0.
  901. // Clients should not need to set this.
  902. @property(atomic, assign) double retryFactor;
  903. // Number of retries attempted.
  904. @property(atomic, readonly) NSUInteger retryCount;
  905. // Interval delay to precede next retry.
  906. @property(atomic, readonly) NSTimeInterval nextRetryInterval;
  907. #if GTM_BACKGROUND_TASK_FETCHING
  908. // Skip use of a UIBackgroundTask, thus requiring fetches to complete when the app is in the
  909. // foreground.
  910. //
  911. // Targets should define GTM_BACKGROUND_TASK_FETCHING to 0 to avoid use of a UIBackgroundTask
  912. // on iOS to allow fetches to complete in the background. This property is available when
  913. // it's not practical to set the preprocessor define.
  914. @property(atomic, assign) BOOL skipBackgroundTask;
  915. #endif // GTM_BACKGROUND_TASK_FETCHING
  916. // Begin fetching the request
  917. //
  918. // The delegate may optionally implement the callback or pass nil for the selector or handler.
  919. //
  920. // The delegate and all callback blocks are retained between the beginFetch call until after the
  921. // finish callback, or until the fetch is stopped.
  922. //
  923. // An error is passed to the callback for server statuses 300 or
  924. // higher, with the status stored as the error object's code.
  925. //
  926. // finishedSEL has a signature like:
  927. // - (void)fetcher:(GTMSessionFetcher *)fetcher
  928. // finishedWithData:(NSData *)data
  929. // error:(NSError *)error;
  930. //
  931. // If the application has specified a destinationFileURL or an accumulateDataBlock
  932. // for the fetcher, the data parameter passed to the callback will be nil.
  933. - (void)beginFetchWithDelegate:(GTM_NULLABLE id)delegate
  934. didFinishSelector:(GTM_NULLABLE SEL)finishedSEL;
  935. - (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler;
  936. // Returns YES if this fetcher is in the process of fetching a URL.
  937. @property(atomic, readonly, getter=isFetching) BOOL fetching;
  938. // Cancel the fetch of the request that's currently in progress. The completion handler
  939. // will not be called.
  940. - (void)stopFetching;
  941. // A block to be called when the fetch completes.
  942. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherCompletionHandler completionHandler;
  943. // A block to be called if download resume data becomes available.
  944. @property(atomic, strong, GTM_NULLABLE) void (^resumeDataBlock)(NSData *);
  945. // Return the status code from the server response.
  946. @property(atomic, readonly) NSInteger statusCode;
  947. // Return the http headers from the response.
  948. @property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *responseHeaders;
  949. // The response, once it's been received.
  950. @property(atomic, strong, readonly, GTM_NULLABLE) NSURLResponse *response;
  951. // Bytes downloaded so far.
  952. @property(atomic, readonly) int64_t downloadedLength;
  953. // Buffer of currently-downloaded data, if available.
  954. @property(atomic, readonly, strong, GTM_NULLABLE) NSData *downloadedData;
  955. // Local path to which the downloaded file will be moved.
  956. //
  957. // If a file already exists at the path, it will be overwritten.
  958. // Will create the enclosing folders if they are not present.
  959. @property(atomic, strong, GTM_NULLABLE) NSURL *destinationFileURL;
  960. // The time this fetcher originally began fetching. This is useful as a time
  961. // barrier for ignoring irrelevant fetch notifications or callbacks.
  962. @property(atomic, strong, readonly, GTM_NULLABLE) NSDate *initialBeginFetchDate;
  963. // userData is retained solely for the convenience of the client.
  964. @property(atomic, strong, GTM_NULLABLE) id userData;
  965. // Stored property values are retained solely for the convenience of the client.
  966. @property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties;
  967. - (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key; // Pass nil for obj to remove the property.
  968. - (GTM_NULLABLE id)propertyForKey:(NSString *)key;
  969. - (void)addPropertiesFromDictionary:(GTM_NSDictionaryOf(NSString *, id) *)dict;
  970. // Comments are useful for logging, so are strongly recommended for each fetcher.
  971. @property(atomic, copy, GTM_NULLABLE) NSString *comment;
  972. - (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2);
  973. // Log of request and response, if logging is enabled
  974. @property(atomic, copy, GTM_NULLABLE) NSString *log;
  975. // Callbacks are run on this queue. If none is supplied, the main queue is used.
  976. @property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue;
  977. // The queue used internally by the session to invoke its delegate methods in the fetcher.
  978. //
  979. // Application callbacks are always called by the fetcher on the callbackQueue above,
  980. // not on this queue. Apps should generally not change this queue.
  981. //
  982. // The default delegate queue is the main queue.
  983. //
  984. // This value is ignored after the session has been created, so this
  985. // property should be set in the fetcher service rather in the fetcher as it applies
  986. // to a shared session.
  987. @property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue;
  988. // Spin the run loop or sleep the thread, discarding events, until the fetch has completed.
  989. //
  990. // This is only for use in testing or in tools without a user interface.
  991. //
  992. // Note: Synchronous fetches should never be used by shipping apps; they are
  993. // sufficient reason for rejection from the app store.
  994. //
  995. // Returns NO if timed out.
  996. - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds;
  997. // Test block is optional for testing.
  998. //
  999. // If present, this block will cause the fetcher to skip starting the session, and instead
  1000. // use the test block response values when calling the completion handler and delegate code.
  1001. //
  1002. // Test code can set this on the fetcher or on the fetcher service. For testing libraries
  1003. // that use a fetcher without exposing either the fetcher or the fetcher service, the global
  1004. // method setGlobalTestBlock: will set the block for all fetchers that do not have a test
  1005. // block set.
  1006. //
  1007. // The test code can pass nil for all response parameters to indicate that the fetch
  1008. // should proceed.
  1009. //
  1010. // Applications can exclude test block support by setting GTM_DISABLE_FETCHER_TEST_BLOCK.
  1011. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock;
  1012. + (void)setGlobalTestBlock:(GTM_NULLABLE GTMSessionFetcherTestBlock)block;
  1013. // When using the testBlock, |testBlockAccumulateDataChunkCount| is the desired number of chunks to
  1014. // divide the response data into if the client has streaming enabled. The data will be divided up to
  1015. // |testBlockAccumulateDataChunkCount| chunks; however, the exact amount may vary depending on the
  1016. // size of the response data (e.g. a 1-byte response can only be divided into one chunk).
  1017. @property(atomic, readwrite) NSUInteger testBlockAccumulateDataChunkCount;
  1018. #if GTM_BACKGROUND_TASK_FETCHING
  1019. // For testing or to override UIApplication invocations, apps may specify an alternative
  1020. // target for messages to UIApplication.
  1021. + (void)setSubstituteUIApplication:(nullable id<GTMUIApplicationProtocol>)substituteUIApplication;
  1022. + (nullable id<GTMUIApplicationProtocol>)substituteUIApplication;
  1023. #endif // GTM_BACKGROUND_TASK_FETCHING
  1024. // Exposed for testing.
  1025. + (GTMSessionCookieStorage *)staticCookieStorage;
  1026. + (BOOL)appAllowsInsecureRequests;
  1027. #if STRIP_GTM_FETCH_LOGGING
  1028. // If logging is stripped, provide a stub for the main method
  1029. // for controlling logging.
  1030. + (void)setLoggingEnabled:(BOOL)flag;
  1031. + (BOOL)isLoggingEnabled;
  1032. #else
  1033. // These methods let an application log specific body text, such as the text description of a binary
  1034. // request or response. The application should set the fetcher to defer response body logging until
  1035. // the response has been received and the log response body has been set by the app. For example:
  1036. //
  1037. // fetcher.logRequestBody = [binaryObject stringDescription];
  1038. // fetcher.deferResponseBodyLogging = YES;
  1039. // [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  1040. // if (error == nil) {
  1041. // fetcher.logResponseBody = [[[MyThing alloc] initWithData:data] stringDescription];
  1042. // }
  1043. // fetcher.deferResponseBodyLogging = NO;
  1044. // }];
  1045. @property(atomic, copy, GTM_NULLABLE) NSString *logRequestBody;
  1046. @property(atomic, assign) BOOL deferResponseBodyLogging;
  1047. @property(atomic, copy, GTM_NULLABLE) NSString *logResponseBody;
  1048. // Internal logging support.
  1049. @property(atomic, readonly) NSData *loggedStreamData;
  1050. @property(atomic, assign) BOOL hasLoggedError;
  1051. @property(atomic, strong, GTM_NULLABLE) NSURL *redirectedFromURL;
  1052. - (void)appendLoggedStreamData:(NSData *)dataToAdd;
  1053. - (void)clearLoggedStreamData;
  1054. #endif // STRIP_GTM_FETCH_LOGGING
  1055. @end
  1056. @interface GTMSessionFetcher (BackwardsCompatibilityOnly)
  1057. // Clients using GTMSessionFetcher should set the cookie storage explicitly themselves.
  1058. // This method is just for compatibility with the old GTMHTTPFetcher class.
  1059. - (void)setCookieStorageMethod:(NSInteger)method;
  1060. @end
  1061. // Until we can just instantiate NSHTTPCookieStorage for local use, we'll
  1062. // implement all the public methods ourselves. This stores cookies only in
  1063. // memory. Additional methods are provided for testing.
  1064. //
  1065. // iOS 9/OS X 10.11 added +[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:]
  1066. // which may also be used to create cookie storage.
  1067. @interface GTMSessionCookieStorage : NSHTTPCookieStorage
  1068. // Add the array off cookies to the storage, replacing duplicates.
  1069. // Also removes expired cookies from the storage.
  1070. - (void)setCookies:(GTM_NULLABLE GTM_NSArrayOf(NSHTTPCookie *) *)cookies;
  1071. - (void)removeAllCookies;
  1072. @end
  1073. // Macros to monitor synchronization blocks in debug builds.
  1074. // These report problems using GTMSessionCheckDebug.
  1075. //
  1076. // GTMSessionMonitorSynchronized Start monitoring a top-level-only
  1077. // @sync scope.
  1078. // GTMSessionMonitorRecursiveSynchronized Start monitoring a top-level or
  1079. // recursive @sync scope.
  1080. // GTMSessionCheckSynchronized Verify that the current execution
  1081. // is inside a @sync scope.
  1082. // GTMSessionCheckNotSynchronized Verify that the current execution
  1083. // is not inside a @sync scope.
  1084. //
  1085. // Example usage:
  1086. //
  1087. // - (void)myExternalMethod {
  1088. // @synchronized(self) {
  1089. // GTMSessionMonitorSynchronized(self)
  1090. //
  1091. // - (void)myInternalMethod {
  1092. // GTMSessionCheckSynchronized(self);
  1093. //
  1094. // - (void)callMyCallbacks {
  1095. // GTMSessionCheckNotSynchronized(self);
  1096. //
  1097. // GTMSessionCheckNotSynchronized is available for verifying the code isn't
  1098. // in a deadlockable @sync state when posting notifications and invoking
  1099. // callbacks. Don't use GTMSessionCheckNotSynchronized immediately before a
  1100. // @sync scope; the normal recursiveness check of GTMSessionMonitorSynchronized
  1101. // can catch those.
  1102. #ifdef __OBJC__
  1103. // If asserts are entirely no-ops, the synchronization monitor is just a bunch
  1104. // of counting code that doesn't report exceptional circumstances in any way.
  1105. // Only build the synchronization monitor code if NS_BLOCK_ASSERTIONS is not
  1106. // defined or asserts are being logged instead.
  1107. #if DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG)
  1108. #define __GTMSessionMonitorSynchronizedVariableInner(varname, counter) \
  1109. varname ## counter
  1110. #define __GTMSessionMonitorSynchronizedVariable(varname, counter) \
  1111. __GTMSessionMonitorSynchronizedVariableInner(varname, counter)
  1112. #define GTMSessionMonitorSynchronized(obj) \
  1113. NS_VALID_UNTIL_END_OF_SCOPE id \
  1114. __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
  1115. [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
  1116. allowRecursive:NO \
  1117. functionName:__func__]
  1118. #define GTMSessionMonitorRecursiveSynchronized(obj) \
  1119. NS_VALID_UNTIL_END_OF_SCOPE id \
  1120. __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
  1121. [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
  1122. allowRecursive:YES \
  1123. functionName:__func__]
  1124. #define GTMSessionCheckSynchronized(obj) { \
  1125. GTMSESSION_ASSERT_DEBUG( \
  1126. [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1127. @"GTMSessionCheckSynchronized(" #obj ") failed: not sync'd" \
  1128. @" on " #obj " in %s. Call stack:\n%@", \
  1129. __func__, [NSThread callStackSymbols]); \
  1130. }
  1131. #define GTMSessionCheckNotSynchronized(obj) { \
  1132. GTMSESSION_ASSERT_DEBUG( \
  1133. ![GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1134. @"GTMSessionCheckNotSynchronized(" #obj ") failed: was sync'd" \
  1135. @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \
  1136. [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1137. [NSThread callStackSymbols]); \
  1138. }
  1139. // GTMSessionSyncMonitorInternal is a private class that keeps track of the
  1140. // beginning and end of synchronized scopes.
  1141. //
  1142. // This class should not be used directly, but only via the
  1143. // GTMSessionMonitorSynchronized macro.
  1144. @interface GTMSessionSyncMonitorInternal : NSObject
  1145. - (instancetype)initWithSynchronizationObject:(id)object
  1146. allowRecursive:(BOOL)allowRecursive
  1147. functionName:(const char *)functionName;
  1148. // Return the names of the functions that hold sync on the object, or nil if none.
  1149. + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object;
  1150. @end
  1151. #else
  1152. #define GTMSessionMonitorSynchronized(obj) do { } while (0)
  1153. #define GTMSessionMonitorRecursiveSynchronized(obj) do { } while (0)
  1154. #define GTMSessionCheckSynchronized(obj) do { } while (0)
  1155. #define GTMSessionCheckNotSynchronized(obj) do { } while (0)
  1156. #endif // !DEBUG
  1157. #endif // __OBJC__
  1158. GTM_ASSUME_NONNULL_END