PerfURLConnectionWithDelegateStartImmediately.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 "PerfURLConnectionWithDelegateStartImmediately.h"
  16. #import "PerfNetworkConnection+Protected.h"
  17. @interface PerfURLConnectionWithDelegateStartImmediately () <NSURLConnectionDelegate>
  18. @property(nonatomic, copy) NSString *urlString;
  19. @property(nonatomic, copy) SuccessNetworkCallback successCallback;
  20. @property(nonatomic, copy) FailureNetworkCallback failureCallback;
  21. @property(nonatomic, strong) NSURLConnection *URLConnection;
  22. @end
  23. @implementation PerfURLConnectionWithDelegateStartImmediately
  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. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlString]];
  31. self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
  32. delegate:self
  33. startImmediately:YES];
  34. }
  35. #pragma mark - NSURLConnectionDelegate methods
  36. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  37. [self logOperationFail];
  38. self.failureCallback(error);
  39. [self clearCallbacks];
  40. }
  41. #pragma mark - NSURLConnectionDataDelegate methods
  42. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  43. [self logOperationSuccess];
  44. self.successCallback();
  45. [self clearCallbacks];
  46. }
  47. #pragma mark - Private methods
  48. - (void)clearCallbacks {
  49. self.failureCallback = nil;
  50. self.successCallback = nil;
  51. }
  52. @end