PerfURLSessionDataTaskWithDelegate.m 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 "PerfURLSessionDataTaskWithDelegate.h"
  16. #import "PerfNetworkConnection+Protected.h"
  17. @interface PerfURLSessionDataTaskWithDelegate () <NSURLSessionDataDelegate>
  18. @property(nonatomic, copy) NSString *urlString;
  19. @property(nonatomic, copy) SuccessNetworkCallback successCallback;
  20. @property(nonatomic, copy) FailureNetworkCallback failureCallback;
  21. @end
  22. @implementation PerfURLSessionDataTaskWithDelegate
  23. #pragma mark - NetworkConnection
  24. - (void)makeNetworkRequestWithSuccessCallback:(SuccessNetworkCallback)success
  25. failureCallback:(FailureNetworkCallback)fail {
  26. [self logOperationStart];
  27. self.successCallback = success;
  28. self.failureCallback = fail;
  29. NSURLSessionConfiguration *configuration =
  30. [NSURLSessionConfiguration defaultSessionConfiguration];
  31. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
  32. delegate:self
  33. delegateQueue:[NSOperationQueue mainQueue]];
  34. NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:self.urlString]];
  35. [dataTask resume];
  36. }
  37. #pragma mark - NSURLSessionDelegate
  38. - (void)URLSession:(NSURLSession *)session
  39. task:(NSURLSessionTask *)task
  40. didCompleteWithError:(NSError *)error {
  41. if (error) {
  42. [self logOperationFail];
  43. self.failureCallback(error);
  44. } else {
  45. [self logOperationSuccess];
  46. self.successCallback();
  47. }
  48. self.failureCallback = nil;
  49. self.successCallback = nil;
  50. [session finishTasksAndInvalidate];
  51. }
  52. @end