You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1305 lines
59 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  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. GTM_ASSUME_NONNULL_BEGIN
  408. // Notifications
  409. //
  410. // Fetch started and stopped, and fetch retry delay started and stopped.
  411. extern NSString *const kGTMSessionFetcherStartedNotification;
  412. extern NSString *const kGTMSessionFetcherStoppedNotification;
  413. extern NSString *const kGTMSessionFetcherRetryDelayStartedNotification;
  414. extern NSString *const kGTMSessionFetcherRetryDelayStoppedNotification;
  415. // Completion handler notification. This is intended for use by code capturing
  416. // and replaying fetch requests and results for testing. For fetches where
  417. // destinationFileURL or accumulateDataBlock is set for the fetcher, the data
  418. // will be nil for successful fetches.
  419. //
  420. // This notification is posted on the main thread.
  421. extern NSString *const kGTMSessionFetcherCompletionInvokedNotification;
  422. extern NSString *const kGTMSessionFetcherCompletionDataKey;
  423. extern NSString *const kGTMSessionFetcherCompletionErrorKey;
  424. // Constants for NSErrors created by the fetcher (excluding server status errors,
  425. // and error objects originating in the OS.)
  426. extern NSString *const kGTMSessionFetcherErrorDomain;
  427. // The fetcher turns server error status values (3XX, 4XX, 5XX) into NSErrors
  428. // with domain kGTMSessionFetcherStatusDomain.
  429. //
  430. // Any server response body data accompanying the status error is added to the
  431. // userInfo dictionary with key kGTMSessionFetcherStatusDataKey.
  432. extern NSString *const kGTMSessionFetcherStatusDomain;
  433. extern NSString *const kGTMSessionFetcherStatusDataKey;
  434. extern NSString *const kGTMSessionFetcherStatusDataContentTypeKey;
  435. // When a fetch fails with an error, these keys are included in the error userInfo
  436. // dictionary if retries were attempted.
  437. extern NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey;
  438. extern NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey;
  439. // Background session support requires access to NSUserDefaults.
  440. // If [NSUserDefaults standardUserDefaults] doesn't yield the correct NSUserDefaults for your usage,
  441. // ie for an App Extension, then implement this class/method to return the correct NSUserDefaults.
  442. // https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6
  443. @interface GTMSessionFetcherUserDefaultsFactory : NSObject
  444. + (NSUserDefaults *)fetcherUserDefaults;
  445. @end
  446. #ifdef __cplusplus
  447. }
  448. #endif
  449. typedef NS_ENUM(NSInteger, GTMSessionFetcherError) {
  450. GTMSessionFetcherErrorDownloadFailed = -1,
  451. GTMSessionFetcherErrorUploadChunkUnavailable = -2,
  452. GTMSessionFetcherErrorBackgroundExpiration = -3,
  453. GTMSessionFetcherErrorBackgroundFetchFailed = -4,
  454. GTMSessionFetcherErrorInsecureRequest = -5,
  455. GTMSessionFetcherErrorTaskCreationFailed = -6,
  456. };
  457. typedef NS_ENUM(NSInteger, GTMSessionFetcherStatus) {
  458. // Standard http status codes.
  459. GTMSessionFetcherStatusNotModified = 304,
  460. GTMSessionFetcherStatusBadRequest = 400,
  461. GTMSessionFetcherStatusUnauthorized = 401,
  462. GTMSessionFetcherStatusForbidden = 403,
  463. GTMSessionFetcherStatusPreconditionFailed = 412
  464. };
  465. #ifdef __cplusplus
  466. extern "C" {
  467. #endif
  468. @class GTMSessionCookieStorage;
  469. @class GTMSessionFetcher;
  470. // The configuration block is for modifying the NSURLSessionConfiguration only.
  471. // DO NOT change any fetcher properties in the configuration block.
  472. typedef void (^GTMSessionFetcherConfigurationBlock)(GTMSessionFetcher *fetcher,
  473. NSURLSessionConfiguration *configuration);
  474. typedef void (^GTMSessionFetcherSystemCompletionHandler)(void);
  475. typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data,
  476. NSError * GTM_NULLABLE_TYPE error);
  477. typedef void (^GTMSessionFetcherBodyStreamProviderResponse)(NSInputStream *bodyStream);
  478. typedef void (^GTMSessionFetcherBodyStreamProvider)(GTMSessionFetcherBodyStreamProviderResponse response);
  479. typedef void (^GTMSessionFetcherDidReceiveResponseDispositionBlock)(NSURLSessionResponseDisposition disposition);
  480. typedef void (^GTMSessionFetcherDidReceiveResponseBlock)(NSURLResponse *response,
  481. GTMSessionFetcherDidReceiveResponseDispositionBlock dispositionBlock);
  482. typedef void (^GTMSessionFetcherChallengeDispositionBlock)(NSURLSessionAuthChallengeDisposition disposition,
  483. NSURLCredential * GTM_NULLABLE_TYPE credential);
  484. typedef void (^GTMSessionFetcherChallengeBlock)(GTMSessionFetcher *fetcher,
  485. NSURLAuthenticationChallenge *challenge,
  486. GTMSessionFetcherChallengeDispositionBlock dispositionBlock);
  487. typedef void (^GTMSessionFetcherWillRedirectResponse)(NSURLRequest * GTM_NULLABLE_TYPE redirectedRequest);
  488. typedef void (^GTMSessionFetcherWillRedirectBlock)(NSHTTPURLResponse *redirectResponse,
  489. NSURLRequest *redirectRequest,
  490. GTMSessionFetcherWillRedirectResponse response);
  491. typedef void (^GTMSessionFetcherAccumulateDataBlock)(NSData * GTM_NULLABLE_TYPE buffer);
  492. typedef void (^GTMSessionFetcherSimulateByteTransferBlock)(NSData * GTM_NULLABLE_TYPE buffer,
  493. int64_t bytesWritten,
  494. int64_t totalBytesWritten,
  495. int64_t totalBytesExpectedToWrite);
  496. typedef void (^GTMSessionFetcherReceivedProgressBlock)(int64_t bytesWritten,
  497. int64_t totalBytesWritten);
  498. typedef void (^GTMSessionFetcherDownloadProgressBlock)(int64_t bytesWritten,
  499. int64_t totalBytesWritten,
  500. int64_t totalBytesExpectedToWrite);
  501. typedef void (^GTMSessionFetcherSendProgressBlock)(int64_t bytesSent,
  502. int64_t totalBytesSent,
  503. int64_t totalBytesExpectedToSend);
  504. typedef void (^GTMSessionFetcherWillCacheURLResponseResponse)(NSCachedURLResponse * GTM_NULLABLE_TYPE cachedResponse);
  505. typedef void (^GTMSessionFetcherWillCacheURLResponseBlock)(NSCachedURLResponse *proposedResponse,
  506. GTMSessionFetcherWillCacheURLResponseResponse responseBlock);
  507. typedef void (^GTMSessionFetcherRetryResponse)(BOOL shouldRetry);
  508. typedef void (^GTMSessionFetcherRetryBlock)(BOOL suggestedWillRetry,
  509. NSError * GTM_NULLABLE_TYPE error,
  510. GTMSessionFetcherRetryResponse response);
  511. typedef void (^GTMSessionFetcherTestResponse)(NSHTTPURLResponse * GTM_NULLABLE_TYPE response,
  512. NSData * GTM_NULLABLE_TYPE data,
  513. NSError * GTM_NULLABLE_TYPE error);
  514. typedef void (^GTMSessionFetcherTestBlock)(GTMSessionFetcher *fetcherToTest,
  515. GTMSessionFetcherTestResponse testResponse);
  516. void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...);
  517. // Utility functions for applications self-identifying to servers via a
  518. // user-agent header
  519. // The "standard" user agent includes the application identifier, taken from the bundle,
  520. // followed by a space and the system version string. Pass nil to use +mainBundle as the source
  521. // of the bundle identifier.
  522. //
  523. // Applications may use this as a starting point for their own user agent strings, perhaps
  524. // with additional sections appended. Use GTMFetcherCleanedUserAgentString() below to
  525. // clean up any string being added to the user agent.
  526. NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle);
  527. // Make a generic name and version for the current application, like
  528. // com.example.MyApp/1.2.3 relying on the bundle identifier and the
  529. // CFBundleShortVersionString or CFBundleVersion.
  530. //
  531. // The bundle ID may be overridden as the base identifier string by
  532. // adding to the bundle's Info.plist a "GTMUserAgentID" key.
  533. //
  534. // If no bundle ID or override is available, the process name preceded
  535. // by "proc_" is used.
  536. NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle);
  537. // Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1"
  538. NSString *GTMFetcherSystemVersionString(void);
  539. // Make a parseable user-agent identifier from the given string, replacing whitespace
  540. // and commas with underscores, and removing other characters that may interfere
  541. // with parsing of the full user-agent string.
  542. //
  543. // For example, @"[My App]" would become @"My_App"
  544. NSString *GTMFetcherCleanedUserAgentString(NSString *str);
  545. // Grab the data from an input stream. Since streams cannot be assumed to be rewindable,
  546. // this may be destructive; the caller can try to rewind the stream (by setting the
  547. // NSStreamFileCurrentOffsetKey property) or can just use the NSData to make a new
  548. // NSInputStream. This function is intended to facilitate testing rather than be used in
  549. // production.
  550. //
  551. // This function operates synchronously on the current thread. Depending on how the
  552. // input stream is implemented, it may be appropriate to dispatch to a different
  553. // queue before calling this function.
  554. //
  555. // Failure is indicated by a returned data value of nil.
  556. NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError);
  557. #ifdef __cplusplus
  558. } // extern "C"
  559. #endif
  560. #if !GTM_USE_SESSION_FETCHER
  561. @protocol GTMHTTPFetcherServiceProtocol;
  562. #endif
  563. // This protocol allows abstract references to the fetcher service, primarily for
  564. // fetchers (which may be compiled without the fetcher service class present.)
  565. //
  566. // Apps should not need to use this protocol.
  567. @protocol GTMSessionFetcherServiceProtocol <NSObject>
  568. // This protocol allows us to call into the service without requiring
  569. // GTMSessionFetcherService sources in this project
  570. @property(atomic, strong) dispatch_queue_t callbackQueue;
  571. - (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher;
  572. - (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher;
  573. - (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher;
  574. - (void)fetcherDidStop:(GTMSessionFetcher *)fetcher;
  575. - (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request;
  576. - (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher;
  577. @property(atomic, assign) BOOL reuseSession;
  578. - (GTM_NULLABLE NSURLSession *)session;
  579. - (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation;
  580. - (GTM_NULLABLE id<NSURLSessionDelegate>)sessionDelegate;
  581. - (GTM_NULLABLE NSDate *)stoppedAllFetchersDate;
  582. // Methods for compatibility with the old GTMHTTPFetcher.
  583. @property(atomic, readonly, strong, GTM_NULLABLE) NSOperationQueue *delegateQueue;
  584. @end // @protocol GTMSessionFetcherServiceProtocol
  585. #ifndef GTM_FETCHER_AUTHORIZATION_PROTOCOL
  586. #define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1
  587. @protocol GTMFetcherAuthorizationProtocol <NSObject>
  588. @required
  589. // This protocol allows us to call the authorizer without requiring its sources
  590. // in this project.
  591. - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request
  592. delegate:(id)delegate
  593. didFinishSelector:(SEL)sel;
  594. - (void)stopAuthorization;
  595. - (void)stopAuthorizationForRequest:(NSURLRequest *)request;
  596. - (BOOL)isAuthorizingRequest:(NSURLRequest *)request;
  597. - (BOOL)isAuthorizedRequest:(NSURLRequest *)request;
  598. @property(atomic, strong, readonly, GTM_NULLABLE) NSString *userEmail;
  599. @optional
  600. // Indicate if authorization may be attempted. Even if this succeeds,
  601. // authorization may fail if the user's permissions have been revoked.
  602. @property(atomic, readonly) BOOL canAuthorize;
  603. // For development only, allow authorization of non-SSL requests, allowing
  604. // transmission of the bearer token unencrypted.
  605. @property(atomic, assign) BOOL shouldAuthorizeAllRequests;
  606. - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request
  607. completionHandler:(void (^)(NSError * GTM_NULLABLE_TYPE error))handler;
  608. #if GTM_USE_SESSION_FETCHER
  609. @property(atomic, weak, GTM_NULLABLE) id<GTMSessionFetcherServiceProtocol> fetcherService;
  610. #else
  611. @property(atomic, weak, GTM_NULLABLE) id<GTMHTTPFetcherServiceProtocol> fetcherService;
  612. #endif
  613. - (BOOL)primeForRefresh;
  614. @end
  615. #endif // GTM_FETCHER_AUTHORIZATION_PROTOCOL
  616. #if GTM_BACKGROUND_TASK_FETCHING
  617. // A protocol for an alternative target for messages from GTMSessionFetcher to UIApplication.
  618. // Set the target using +[GTMSessionFetcher setSubstituteUIApplication:]
  619. @protocol GTMUIApplicationProtocol <NSObject>
  620. - (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName
  621. expirationHandler:(void(^ __nullable)(void))handler;
  622. - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier;
  623. @end
  624. #endif
  625. #pragma mark -
  626. // GTMSessionFetcher objects are used for async retrieval of an http get or post
  627. //
  628. // See additional comments at the beginning of this file
  629. @interface GTMSessionFetcher : NSObject <NSURLSessionDelegate>
  630. // Create a fetcher
  631. //
  632. // fetcherWithRequest will return an autoreleased fetcher, but if
  633. // the connection is successfully created, the connection should retain the
  634. // fetcher for the life of the connection as well. So the caller doesn't have
  635. // to retain the fetcher explicitly unless they want to be able to cancel it.
  636. + (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request;
  637. // Convenience methods that make a request, like +fetcherWithRequest
  638. + (instancetype)fetcherWithURL:(NSURL *)requestURL;
  639. + (instancetype)fetcherWithURLString:(NSString *)requestURLString;
  640. // Methods for creating fetchers to continue previous fetches.
  641. + (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData;
  642. + (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier;
  643. // Returns an array of currently active fetchers for background sessions,
  644. // both restarted and newly created ones.
  645. + (GTM_NSArrayOf(GTMSessionFetcher *) *)fetchersForBackgroundSessions;
  646. // Designated initializer.
  647. //
  648. // Applications should create fetchers with a "fetcherWith..." method on a fetcher
  649. // service or a class method, not with this initializer.
  650. //
  651. // The configuration should typically be nil. Applications needing to customize
  652. // the configuration may do so by setting the configurationBlock property.
  653. - (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request
  654. configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration;
  655. // The fetcher's request. This may not be set after beginFetch has been invoked. The request
  656. // may change due to redirects.
  657. @property(atomic, strong, GTM_NULLABLE) NSURLRequest *request;
  658. // Set a header field value on the request. Header field value changes will not
  659. // affect a fetch after the fetch has begun.
  660. - (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field;
  661. // Data used for resuming a download task.
  662. @property(atomic, readonly, GTM_NULLABLE) NSData *downloadResumeData;
  663. // The configuration; this must be set before the fetch begins. If no configuration is
  664. // set or inherited from the fetcher service, then the fetcher uses an ephemeral config.
  665. //
  666. // NOTE: This property should typically be nil. Applications needing to customize
  667. // the configuration should do so by setting the configurationBlock property.
  668. // That allows the fetcher to pick an appropriate base configuration, with the
  669. // application setting only the configuration properties it needs to customize.
  670. @property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration;
  671. // A block the client may use to customize the configuration used to create the session.
  672. //
  673. // This is called synchronously, either on the thread that begins the fetch or, during a retry,
  674. // on the main thread. The configuration block may be called repeatedly if multiple fetchers are
  675. // created.
  676. //
  677. // The configuration block is for modifying the NSURLSessionConfiguration only.
  678. // DO NOT change any fetcher properties in the configuration block. Fetcher properties
  679. // may be set in the fetcher service prior to fetcher creation, or on the fetcher prior
  680. // to invoking beginFetch.
  681. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock;
  682. // A session is created as needed by the fetcher. A fetcher service object
  683. // may maintain sessions for multiple fetches to the same host.
  684. @property(atomic, strong, GTM_NULLABLE) NSURLSession *session;
  685. // The task in flight.
  686. @property(atomic, readonly, GTM_NULLABLE) NSURLSessionTask *sessionTask;
  687. // The background session identifier.
  688. @property(atomic, readonly, GTM_NULLABLE) NSString *sessionIdentifier;
  689. // Indicates a fetcher created to finish a background session task.
  690. @property(atomic, readonly) BOOL wasCreatedFromBackgroundSession;
  691. // Additional user-supplied data to encode into the session identifier. Since session identifier
  692. // length limits are unspecified, this should be kept small. Key names beginning with an underscore
  693. // are reserved for use by the fetcher.
  694. @property(atomic, strong, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *sessionUserInfo;
  695. // The human-readable description to be assigned to the task.
  696. @property(atomic, copy, GTM_NULLABLE) NSString *taskDescription;
  697. // The priority assigned to the task, if any. Use NSURLSessionTaskPriorityLow,
  698. // NSURLSessionTaskPriorityDefault, or NSURLSessionTaskPriorityHigh.
  699. @property(atomic, assign) float taskPriority;
  700. // The fetcher encodes information used to resume a session in the session identifier.
  701. // This method, intended for internal use returns the encoded information. The sessionUserInfo
  702. // dictionary is stored as identifier metadata.
  703. - (GTM_NULLABLE GTM_NSDictionaryOf(NSString *, NSString *) *)sessionIdentifierMetadata;
  704. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH
  705. // The app should pass to this method the completion handler passed in the app delegate method
  706. // application:handleEventsForBackgroundURLSession:completionHandler:
  707. + (void)application:(UIApplication *)application
  708. handleEventsForBackgroundURLSession:(NSString *)identifier
  709. completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler;
  710. #endif
  711. // Indicate that a newly created session should be a background session.
  712. // A new session identifier will be created by the fetcher.
  713. //
  714. // Warning: The only thing background sessions are for is rare download
  715. // of huge, batched files of data. And even just for those, there's a lot
  716. // of pain and hackery needed to get transfers to actually happen reliably
  717. // with background sessions.
  718. //
  719. // Don't try to upload or download in many background sessions, since the system
  720. // will impose an exponentially increasing time penalty to prevent the app from
  721. // getting too much background execution time.
  722. //
  723. // References:
  724. //
  725. // "Moving to Fewer, Larger Transfers"
  726. // https://forums.developer.apple.com/thread/14853
  727. //
  728. // "NSURLSession’s Resume Rate Limiter"
  729. // https://forums.developer.apple.com/thread/14854
  730. //
  731. // "Background Session Task state persistence"
  732. // https://forums.developer.apple.com/thread/11554
  733. //
  734. @property(atomic, assign) BOOL useBackgroundSession;
  735. // Indicates if the fetcher was started using a background session.
  736. @property(atomic, readonly, getter=isUsingBackgroundSession) BOOL usingBackgroundSession;
  737. // Indicates if uploads should use an upload task. This is always set for file or stream-provider
  738. // bodies, but may be set explicitly for NSData bodies.
  739. @property(atomic, assign) BOOL useUploadTask;
  740. // Indicates that the fetcher is using a session that may be shared with other fetchers.
  741. @property(atomic, readonly) BOOL canShareSession;
  742. // By default, the fetcher allows only secure (https) schemes unless this
  743. // property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set.
  744. //
  745. // For example, during debugging when fetching from a development server that lacks SSL support,
  746. // this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files,
  747. // this may be set to @[ @"file" ].
  748. //
  749. // This should be left as nil for release builds to avoid creating the opportunity for
  750. // leaking private user behavior and data. If a server is providing insecure URLs
  751. // for fetching by the client app, report the problem as server security & privacy bug.
  752. //
  753. // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when
  754. // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist.
  755. @property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes;
  756. // By default, the fetcher prohibits localhost requests unless this property is set,
  757. // or the GTM_ALLOW_INSECURE_REQUESTS build flag is set.
  758. //
  759. // For localhost requests, the URL scheme is not checked when this property is set.
  760. //
  761. // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when
  762. // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist.
  763. @property(atomic, assign) BOOL allowLocalhostRequest;
  764. // By default, the fetcher requires valid server certs. This may be bypassed
  765. // temporarily for development against a test server with an invalid cert.
  766. @property(atomic, assign) BOOL allowInvalidServerCertificates;
  767. // Cookie storage object for this fetcher. If nil, the fetcher will use a static cookie
  768. // storage instance shared among fetchers. If this fetcher was created by a fetcher service
  769. // object, it will be set to use the service object's cookie storage. See Cookies section above for
  770. // the full discussion.
  771. //
  772. // Because as of Jan 2014 standalone instances of NSHTTPCookieStorage do not actually
  773. // store any cookies (Radar 15735276) we use our own subclass, GTMSessionCookieStorage,
  774. // to hold cookies in memory.
  775. @property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage;
  776. // Setting the credential is optional; it is used if the connection receives
  777. // an authentication challenge.
  778. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential;
  779. // Setting the proxy credential is optional; it is used if the connection
  780. // receives an authentication challenge from a proxy.
  781. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *proxyCredential;
  782. // If body data, body file URL, or body stream provider is not set, then a GET request
  783. // method is assumed.
  784. @property(atomic, strong, GTM_NULLABLE) NSData *bodyData;
  785. // File to use as the request body. This forces use of an upload task.
  786. @property(atomic, strong, GTM_NULLABLE) NSURL *bodyFileURL;
  787. // Length of body to send, expected or actual.
  788. @property(atomic, readonly) int64_t bodyLength;
  789. // The body stream provider may be called repeatedly to provide a body.
  790. // Setting a body stream provider forces use of an upload task.
  791. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherBodyStreamProvider bodyStreamProvider;
  792. // Object to add authorization to the request, if needed.
  793. //
  794. // This may not be changed once beginFetch has been invoked.
  795. @property(atomic, strong, GTM_NULLABLE) id<GTMFetcherAuthorizationProtocol> authorizer;
  796. // The service object that created and monitors this fetcher, if any.
  797. @property(atomic, strong) id<GTMSessionFetcherServiceProtocol> service;
  798. // The host, if any, used to classify this fetcher in the fetcher service.
  799. @property(atomic, copy, GTM_NULLABLE) NSString *serviceHost;
  800. // The priority, if any, used for starting fetchers in the fetcher service.
  801. //
  802. // Lower values are higher priority; the default is 0, and values may
  803. // be negative or positive. This priority affects only the start order of
  804. // fetchers that are being delayed by a fetcher service when the running fetchers
  805. // exceeds the service's maxRunningFetchersPerHost. A priority of NSIntegerMin will
  806. // exempt this fetcher from delay.
  807. @property(atomic, assign) NSInteger servicePriority;
  808. // The delegate's optional didReceiveResponse block may be used to inspect or alter
  809. // the session task response.
  810. //
  811. // This is called on the callback queue.
  812. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock;
  813. // The delegate's optional challenge block may be used to inspect or alter
  814. // the session task challenge.
  815. //
  816. // If this block is not set, the fetcher's default behavior for the NSURLSessionTask
  817. // didReceiveChallenge: delegate method is to use the fetcher's respondToChallenge: method
  818. // which relies on the fetcher's credential and proxyCredential properties.
  819. //
  820. // Warning: This may be called repeatedly if the challenge fails. Check
  821. // challenge.previousFailureCount to identify repeated invocations.
  822. //
  823. // This is called on the callback queue.
  824. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock;
  825. // The delegate's optional willRedirect block may be used to inspect or alter
  826. // the redirection.
  827. //
  828. // This is called on the callback queue.
  829. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillRedirectBlock willRedirectBlock;
  830. // The optional send progress block reports body bytes uploaded.
  831. //
  832. // This is called on the callback queue.
  833. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherSendProgressBlock sendProgressBlock;
  834. // The optional accumulate block may be set by clients wishing to accumulate data
  835. // themselves rather than let the fetcher append each buffer to an NSData.
  836. //
  837. // When this is called with nil data (such as on redirect) the client
  838. // should empty its accumulation buffer.
  839. //
  840. // This is called on the callback queue.
  841. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherAccumulateDataBlock accumulateDataBlock;
  842. // The optional received progress block may be used to monitor data
  843. // received from a data task.
  844. //
  845. // This is called on the callback queue.
  846. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherReceivedProgressBlock receivedProgressBlock;
  847. // The delegate's optional downloadProgress block may be used to monitor download
  848. // progress in writing to disk.
  849. //
  850. // This is called on the callback queue.
  851. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDownloadProgressBlock downloadProgressBlock;
  852. // The delegate's optional willCacheURLResponse block may be used to alter the cached
  853. // NSURLResponse. The user may prevent caching by passing nil to the block's response.
  854. //
  855. // This is called on the callback queue.
  856. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock;
  857. // Enable retrying; see comments at the top of this file. Setting
  858. // retryEnabled=YES resets the min and max retry intervals.
  859. @property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled;
  860. // Retry block is optional for retries.
  861. //
  862. // If present, this block should call the response block with YES to cause a retry or NO to end the
  863. // fetch.
  864. // See comments at the top of this file.
  865. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock;
  866. // Retry intervals must be strictly less than maxRetryInterval, else
  867. // they will be limited to maxRetryInterval and no further retries will
  868. // be attempted. Setting maxRetryInterval to 0.0 will reset it to the
  869. // default value, 60 seconds for downloads and 600 seconds for uploads.
  870. @property(atomic, assign) NSTimeInterval maxRetryInterval;
  871. // Starting retry interval. Setting minRetryInterval to 0.0 will reset it
  872. // to a random value between 1.0 and 2.0 seconds. Clients should normally not
  873. // set this except for unit testing.
  874. @property(atomic, assign) NSTimeInterval minRetryInterval;
  875. // Multiplier used to increase the interval between retries, typically 2.0.
  876. // Clients should not need to set this.
  877. @property(atomic, assign) double retryFactor;
  878. // Number of retries attempted.
  879. @property(atomic, readonly) NSUInteger retryCount;
  880. // Interval delay to precede next retry.
  881. @property(atomic, readonly) NSTimeInterval nextRetryInterval;
  882. #if GTM_BACKGROUND_TASK_FETCHING
  883. // Skip use of a UIBackgroundTask, thus requiring fetches to complete when the app is in the
  884. // foreground.
  885. //
  886. // Targets should define GTM_BACKGROUND_TASK_FETCHING to 0 to avoid use of a UIBackgroundTask
  887. // on iOS to allow fetches to complete in the background. This property is available when
  888. // it's not practical to set the preprocessor define.
  889. @property(atomic, assign) BOOL skipBackgroundTask;
  890. #endif // GTM_BACKGROUND_TASK_FETCHING
  891. // Begin fetching the request
  892. //
  893. // The delegate may optionally implement the callback or pass nil for the selector or handler.
  894. //
  895. // The delegate and all callback blocks are retained between the beginFetch call until after the
  896. // finish callback, or until the fetch is stopped.
  897. //
  898. // An error is passed to the callback for server statuses 300 or
  899. // higher, with the status stored as the error object's code.
  900. //
  901. // finishedSEL has a signature like:
  902. // - (void)fetcher:(GTMSessionFetcher *)fetcher
  903. // finishedWithData:(NSData *)data
  904. // error:(NSError *)error;
  905. //
  906. // If the application has specified a destinationFileURL or an accumulateDataBlock
  907. // for the fetcher, the data parameter passed to the callback will be nil.
  908. - (void)beginFetchWithDelegate:(GTM_NULLABLE id)delegate
  909. didFinishSelector:(GTM_NULLABLE SEL)finishedSEL;
  910. - (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler;
  911. // Returns YES if this fetcher is in the process of fetching a URL.
  912. @property(atomic, readonly, getter=isFetching) BOOL fetching;
  913. // Cancel the fetch of the request that's currently in progress. The completion handler
  914. // will not be called.
  915. - (void)stopFetching;
  916. // A block to be called when the fetch completes.
  917. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherCompletionHandler completionHandler;
  918. // A block to be called if download resume data becomes available.
  919. @property(atomic, strong, GTM_NULLABLE) void (^resumeDataBlock)(NSData *);
  920. // Return the status code from the server response.
  921. @property(atomic, readonly) NSInteger statusCode;
  922. // Return the http headers from the response.
  923. @property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *responseHeaders;
  924. // The response, once it's been received.
  925. @property(atomic, strong, readonly, GTM_NULLABLE) NSURLResponse *response;
  926. // Bytes downloaded so far.
  927. @property(atomic, readonly) int64_t downloadedLength;
  928. // Buffer of currently-downloaded data, if available.
  929. @property(atomic, readonly, strong, GTM_NULLABLE) NSData *downloadedData;
  930. // Local path to which the downloaded file will be moved.
  931. //
  932. // If a file already exists at the path, it will be overwritten.
  933. // Will create the enclosing folders if they are not present.
  934. @property(atomic, strong, GTM_NULLABLE) NSURL *destinationFileURL;
  935. // The time this fetcher originally began fetching. This is useful as a time
  936. // barrier for ignoring irrelevant fetch notifications or callbacks.
  937. @property(atomic, strong, readonly, GTM_NULLABLE) NSDate *initialBeginFetchDate;
  938. // userData is retained solely for the convenience of the client.
  939. @property(atomic, strong, GTM_NULLABLE) id userData;
  940. // Stored property values are retained solely for the convenience of the client.
  941. @property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties;
  942. - (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key; // Pass nil for obj to remove the property.
  943. - (GTM_NULLABLE id)propertyForKey:(NSString *)key;
  944. - (void)addPropertiesFromDictionary:(GTM_NSDictionaryOf(NSString *, id) *)dict;
  945. // Comments are useful for logging, so are strongly recommended for each fetcher.
  946. @property(atomic, copy, GTM_NULLABLE) NSString *comment;
  947. - (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2);
  948. // Log of request and response, if logging is enabled
  949. @property(atomic, copy, GTM_NULLABLE) NSString *log;
  950. // Callbacks are run on this queue. If none is supplied, the main queue is used.
  951. @property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue;
  952. // The queue used internally by the session to invoke its delegate methods in the fetcher.
  953. //
  954. // Application callbacks are always called by the fetcher on the callbackQueue above,
  955. // not on this queue. Apps should generally not change this queue.
  956. //
  957. // The default delegate queue is the main queue.
  958. //
  959. // This value is ignored after the session has been created, so this
  960. // property should be set in the fetcher service rather in the fetcher as it applies
  961. // to a shared session.
  962. @property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue;
  963. // Spin the run loop or sleep the thread, discarding events, until the fetch has completed.
  964. //
  965. // This is only for use in testing or in tools without a user interface.
  966. //
  967. // Note: Synchronous fetches should never be used by shipping apps; they are
  968. // sufficient reason for rejection from the app store.
  969. //
  970. // Returns NO if timed out.
  971. - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds;
  972. // Test block is optional for testing.
  973. //
  974. // If present, this block will cause the fetcher to skip starting the session, and instead
  975. // use the test block response values when calling the completion handler and delegate code.
  976. //
  977. // Test code can set this on the fetcher or on the fetcher service. For testing libraries
  978. // that use a fetcher without exposing either the fetcher or the fetcher service, the global
  979. // method setGlobalTestBlock: will set the block for all fetchers that do not have a test
  980. // block set.
  981. //
  982. // The test code can pass nil for all response parameters to indicate that the fetch
  983. // should proceed.
  984. //
  985. // Applications can exclude test block support by setting GTM_DISABLE_FETCHER_TEST_BLOCK.
  986. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock;
  987. + (void)setGlobalTestBlock:(GTM_NULLABLE GTMSessionFetcherTestBlock)block;
  988. // When using the testBlock, |testBlockAccumulateDataChunkCount| is the desired number of chunks to
  989. // divide the response data into if the client has streaming enabled. The data will be divided up to
  990. // |testBlockAccumulateDataChunkCount| chunks; however, the exact amount may vary depending on the
  991. // size of the response data (e.g. a 1-byte response can only be divided into one chunk).
  992. @property(atomic, readwrite) NSUInteger testBlockAccumulateDataChunkCount;
  993. #if GTM_BACKGROUND_TASK_FETCHING
  994. // For testing or to override UIApplication invocations, apps may specify an alternative
  995. // target for messages to UIApplication.
  996. + (void)setSubstituteUIApplication:(nullable id<GTMUIApplicationProtocol>)substituteUIApplication;
  997. + (nullable id<GTMUIApplicationProtocol>)substituteUIApplication;
  998. #endif // GTM_BACKGROUND_TASK_FETCHING
  999. // Exposed for testing.
  1000. + (GTMSessionCookieStorage *)staticCookieStorage;
  1001. + (BOOL)appAllowsInsecureRequests;
  1002. #if STRIP_GTM_FETCH_LOGGING
  1003. // If logging is stripped, provide a stub for the main method
  1004. // for controlling logging.
  1005. + (void)setLoggingEnabled:(BOOL)flag;
  1006. + (BOOL)isLoggingEnabled;
  1007. #else
  1008. // These methods let an application log specific body text, such as the text description of a binary
  1009. // request or response. The application should set the fetcher to defer response body logging until
  1010. // the response has been received and the log response body has been set by the app. For example:
  1011. //
  1012. // fetcher.logRequestBody = [binaryObject stringDescription];
  1013. // fetcher.deferResponseBodyLogging = YES;
  1014. // [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  1015. // if (error == nil) {
  1016. // fetcher.logResponseBody = [[[MyThing alloc] initWithData:data] stringDescription];
  1017. // }
  1018. // fetcher.deferResponseBodyLogging = NO;
  1019. // }];
  1020. @property(atomic, copy, GTM_NULLABLE) NSString *logRequestBody;
  1021. @property(atomic, assign) BOOL deferResponseBodyLogging;
  1022. @property(atomic, copy, GTM_NULLABLE) NSString *logResponseBody;
  1023. // Internal logging support.
  1024. @property(atomic, readonly) NSData *loggedStreamData;
  1025. @property(atomic, assign) BOOL hasLoggedError;
  1026. @property(atomic, strong, GTM_NULLABLE) NSURL *redirectedFromURL;
  1027. - (void)appendLoggedStreamData:(NSData *)dataToAdd;
  1028. - (void)clearLoggedStreamData;
  1029. #endif // STRIP_GTM_FETCH_LOGGING
  1030. @end
  1031. @interface GTMSessionFetcher (BackwardsCompatibilityOnly)
  1032. // Clients using GTMSessionFetcher should set the cookie storage explicitly themselves.
  1033. // This method is just for compatibility with the old GTMHTTPFetcher class.
  1034. - (void)setCookieStorageMethod:(NSInteger)method;
  1035. @end
  1036. // Until we can just instantiate NSHTTPCookieStorage for local use, we'll
  1037. // implement all the public methods ourselves. This stores cookies only in
  1038. // memory. Additional methods are provided for testing.
  1039. //
  1040. // iOS 9/OS X 10.11 added +[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:]
  1041. // which may also be used to create cookie storage.
  1042. @interface GTMSessionCookieStorage : NSHTTPCookieStorage
  1043. // Add the array off cookies to the storage, replacing duplicates.
  1044. // Also removes expired cookies from the storage.
  1045. - (void)setCookies:(GTM_NULLABLE GTM_NSArrayOf(NSHTTPCookie *) *)cookies;
  1046. - (void)removeAllCookies;
  1047. @end
  1048. // Macros to monitor synchronization blocks in debug builds.
  1049. // These report problems using GTMSessionCheckDebug.
  1050. //
  1051. // GTMSessionMonitorSynchronized Start monitoring a top-level-only
  1052. // @sync scope.
  1053. // GTMSessionMonitorRecursiveSynchronized Start monitoring a top-level or
  1054. // recursive @sync scope.
  1055. // GTMSessionCheckSynchronized Verify that the current execution
  1056. // is inside a @sync scope.
  1057. // GTMSessionCheckNotSynchronized Verify that the current execution
  1058. // is not inside a @sync scope.
  1059. //
  1060. // Example usage:
  1061. //
  1062. // - (void)myExternalMethod {
  1063. // @synchronized(self) {
  1064. // GTMSessionMonitorSynchronized(self)
  1065. //
  1066. // - (void)myInternalMethod {
  1067. // GTMSessionCheckSynchronized(self);
  1068. //
  1069. // - (void)callMyCallbacks {
  1070. // GTMSessionCheckNotSynchronized(self);
  1071. //
  1072. // GTMSessionCheckNotSynchronized is available for verifying the code isn't
  1073. // in a deadlockable @sync state when posting notifications and invoking
  1074. // callbacks. Don't use GTMSessionCheckNotSynchronized immediately before a
  1075. // @sync scope; the normal recursiveness check of GTMSessionMonitorSynchronized
  1076. // can catch those.
  1077. #ifdef __OBJC__
  1078. // If asserts are entirely no-ops, the synchronization monitor is just a bunch
  1079. // of counting code that doesn't report exceptional circumstances in any way.
  1080. // Only build the synchronization monitor code if NS_BLOCK_ASSERTIONS is not
  1081. // defined or asserts are being logged instead.
  1082. #if DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG)
  1083. #define __GTMSessionMonitorSynchronizedVariableInner(varname, counter) \
  1084. varname ## counter
  1085. #define __GTMSessionMonitorSynchronizedVariable(varname, counter) \
  1086. __GTMSessionMonitorSynchronizedVariableInner(varname, counter)
  1087. #define GTMSessionMonitorSynchronized(obj) \
  1088. NS_VALID_UNTIL_END_OF_SCOPE id \
  1089. __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
  1090. [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
  1091. allowRecursive:NO \
  1092. functionName:__func__]
  1093. #define GTMSessionMonitorRecursiveSynchronized(obj) \
  1094. NS_VALID_UNTIL_END_OF_SCOPE id \
  1095. __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \
  1096. [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \
  1097. allowRecursive:YES \
  1098. functionName:__func__]
  1099. #define GTMSessionCheckSynchronized(obj) { \
  1100. GTMSESSION_ASSERT_DEBUG( \
  1101. [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1102. @"GTMSessionCheckSynchronized(" #obj ") failed: not sync'd" \
  1103. @" on " #obj " in %s. Call stack:\n%@", \
  1104. __func__, [NSThread callStackSymbols]); \
  1105. }
  1106. #define GTMSessionCheckNotSynchronized(obj) { \
  1107. GTMSESSION_ASSERT_DEBUG( \
  1108. ![GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1109. @"GTMSessionCheckNotSynchronized(" #obj ") failed: was sync'd" \
  1110. @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \
  1111. [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \
  1112. [NSThread callStackSymbols]); \
  1113. }
  1114. // GTMSessionSyncMonitorInternal is a private class that keeps track of the
  1115. // beginning and end of synchronized scopes.
  1116. //
  1117. // This class should not be used directly, but only via the
  1118. // GTMSessionMonitorSynchronized macro.
  1119. @interface GTMSessionSyncMonitorInternal : NSObject
  1120. - (instancetype)initWithSynchronizationObject:(id)object
  1121. allowRecursive:(BOOL)allowRecursive
  1122. functionName:(const char *)functionName;
  1123. // Return the names of the functions that hold sync on the object, or nil if none.
  1124. + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object;
  1125. @end
  1126. #else
  1127. #define GTMSessionMonitorSynchronized(obj) do { } while (0)
  1128. #define GTMSessionMonitorRecursiveSynchronized(obj) do { } while (0)
  1129. #define GTMSessionCheckSynchronized(obj) do { } while (0)
  1130. #define GTMSessionCheckNotSynchronized(obj) do { } while (0)
  1131. #endif // !DEBUG
  1132. #endif // __OBJC__
  1133. GTM_ASSUME_NONNULL_END