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.

1308 lines
58 KiB

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