PerfURLSessionDownloadTaskWithDelegate.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2020 Google LLC
  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. // Non-google3 relative import to support building with Xcode.
  15. #import "PerfURLSessionDownloadTaskWithDelegate.h"
  16. #import "../Models/PerfLogger.h"
  17. #import "PerfNetworkConnection+Protected.h"
  18. @interface PerfURLSessionDownloadTaskWithDelegate () <NSURLSessionDataDelegate>
  19. @property(nonatomic, copy) NSString *urlString;
  20. @property(nonatomic, copy) SuccessNetworkCallback successCallback;
  21. @property(nonatomic, copy) FailureNetworkCallback failureCallback;
  22. @end
  23. @implementation PerfURLSessionDownloadTaskWithDelegate
  24. #pragma mark - NetworkConnection
  25. - (void)makeNetworkRequestWithSuccessCallback:(SuccessNetworkCallback)success
  26. failureCallback:(FailureNetworkCallback)fail {
  27. [self logOperationStart];
  28. self.successCallback = success;
  29. self.failureCallback = fail;
  30. NSURLSessionConfiguration *configuration =
  31. [NSURLSessionConfiguration defaultSessionConfiguration];
  32. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
  33. delegate:self
  34. delegateQueue:[NSOperationQueue mainQueue]];
  35. NSURLSessionDownloadTask *downloadTask =
  36. [session downloadTaskWithURL:[NSURL URLWithString:self.urlString]];
  37. [downloadTask resume];
  38. }
  39. #pragma mark - NSURLSessionDelegate
  40. - (void)URLSession:(NSURLSession *)session
  41. task:(NSURLSessionTask *)task
  42. didCompleteWithError:(NSError *)error {
  43. if (error) {
  44. [self logOperationFail];
  45. self.failureCallback(error);
  46. } else {
  47. [self logOperationSuccess];
  48. self.successCallback();
  49. }
  50. self.failureCallback = nil;
  51. self.successCallback = nil;
  52. [session finishTasksAndInvalidate];
  53. PerfLog(@" FinishTasksAndInvalidate completed");
  54. }
  55. @end