MiscNetworkRequests.m 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. //
  2. // MiscNetworkRequests.m
  3. // FLEXample
  4. //
  5. // Created by Tanner on 3/12/20.
  6. // Copyright © 2020 Flipboard. All rights reserved.
  7. //
  8. #import "MiscNetworkRequests.h"
  9. @implementation MiscNetworkRequests
  10. + (void)sendExampleRequests {
  11. [[self new] sendExampleNetworkRequests];
  12. }
  13. - (NSMutableURLRequest *)request:(NSString *)url {
  14. return [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  15. }
  16. - (void)sendExampleNetworkRequests {
  17. NSString *kFlipboardIcon = @"https://cdn.flipboard.com/serviceIcons/v2/social-icon-flipboard-96.png";
  18. NSString *kRandomAnimal = @"https://lorempixel.com/248/250/animals/";
  19. NSString *kSnowLeopard = @"https://lorempixel.com/248/250/animals/4/";
  20. NSString *kRateLimit = @"https://api.github.com/rate_limit";
  21. NSString *kImgurUpload = @"https://api.imgur.com/3/upload";
  22. //#######################
  23. // #
  24. // NSURLSession #
  25. // #
  26. //#######################
  27. NSMutableArray *pendingTasks = [NSMutableArray array];
  28. // With delegate //
  29. NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
  30. config.timeoutIntervalForRequest = 10.0;
  31. NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
  32. // NSURLSessionDataTask
  33. [pendingTasks addObject:[session dataTaskWithURL:[NSURL URLWithString:kFlipboardIcon]]];
  34. // NSURLSessionDownloadTask
  35. [pendingTasks addObject:[session downloadTaskWithURL:[NSURL URLWithString:kRandomAnimal]]];
  36. // Without delegate //
  37. // NSURLSessionDownloadTask
  38. [pendingTasks addObject:[NSURLSession.sharedSession
  39. downloadTaskWithURL:[NSURL URLWithString:kSnowLeopard]
  40. completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  41. NSInteger status = [(NSHTTPURLResponse *)response statusCode];
  42. if (status == 200) {
  43. NSLog(@"Image downloaded to %@", location.absoluteString);
  44. } else {
  45. NSLog(@"Image failed to download with status %@ (error: %@)",
  46. @(status), error.localizedDescription
  47. );
  48. }
  49. }
  50. ]];
  51. // NSURLSessionDataTask
  52. [pendingTasks addObject:[NSURLSession.sharedSession
  53. dataTaskWithURL:[NSURL URLWithString:kRateLimit]
  54. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  55. }]];
  56. // NSURLSessionUploadTask
  57. NSMutableURLRequest *upload = [self request:kImgurUpload];
  58. upload.HTTPMethod = @"POST";
  59. [upload setValue:@"Client-ID 0e8a1cb2eb594ef" forHTTPHeaderField:@"Authorization"];
  60. [pendingTasks addObject:[session
  61. uploadTaskWithRequest:upload
  62. fromFile:[NSBundle.mainBundle URLForResource:@"image" withExtension:@"jpg"]
  63. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  64. NSInteger status = [(NSHTTPURLResponse *)response statusCode];
  65. if (status == 200) {
  66. NSError *jsonError = nil;
  67. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
  68. if (json) {
  69. NSLog(@"Image uploaded to %@", json[@"data"][@"link"]);
  70. } else {
  71. NSLog(@"Error decoding JSON after uploading image: %@", jsonError.localizedDescription);
  72. }
  73. } else if (data) {
  74. NSError *jsonError = nil;
  75. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
  76. if (json) {
  77. NSLog(@"Image failed to upload with error: %@", json[@"data"][@"error"]);
  78. } else {
  79. NSLog(@"Error decoding JSON after failing to upload image: %@", jsonError.localizedDescription);
  80. }
  81. } else {
  82. NSLog(@"Error uploading image: %@", error.localizedDescription);
  83. }
  84. }
  85. ]];
  86. NSTimeInterval delayTime = 5;
  87. const NSTimeInterval stagger = 1;
  88. // Stagger each task
  89. for (NSURLSessionTask *task in pendingTasks) {
  90. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  91. [task resume];
  92. });
  93. delayTime += stagger;
  94. }
  95. //########################
  96. // #
  97. // NSURLConnection #
  98. // #
  99. //########################
  100. #pragma clang diagnostic push
  101. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  102. // Remaining requests made through NSURLConnection with a delegate
  103. NSArray *requestURLStrings = @[ @"https://lorempixel.com/400/400/",
  104. @"https://google.com",
  105. @"https://api.github.com/users/Flipboard/repos",
  106. @"https://api.github.com/repos/Flipboard/FLEX/issues",
  107. @"https://cloud.githubusercontent.com/assets/516562/3971767/e4e21f58-27d6-11e4-9b07-4d1fe82b80ca.png",
  108. @"https://lorempixel.com/750/1334/" ];
  109. // Async NSURLConnection
  110. [NSURLConnection sendAsynchronousRequest:[self request:@"https://api.github.com/repos/Flipboard/FLEX/issues"]
  111. queue:NSOperationQueue.mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
  112. }];
  113. // Begin staggering NSURLConnection requests
  114. self.connections = [NSMutableArray array];
  115. for (NSString *urlString in requestURLStrings) {
  116. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  117. [self.connections addObject:[NSURLConnection connectionWithRequest:[self request:urlString] delegate:self]];
  118. });
  119. delayTime += stagger;
  120. }
  121. #pragma clang diagnostic pop
  122. }
  123. - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
  124. NSLog(@"URLSession didBecomeInvalidWithError: %@", error.localizedDescription);
  125. }
  126. - (void)URLSession:(NSURLSession *)session
  127. dataTask:(NSURLSessionDataTask *)dataTask
  128. didReceiveResponse:(NSURLResponse *)response
  129. completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
  130. completionHandler(NSURLSessionResponseAllow);
  131. }
  132. - (void)URLSession:(NSURLSession *)session
  133. downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
  134. NSLog(@"didFinishDownloadingToURL: %@", location.absoluteString);
  135. }
  136. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  137. [self.connections removeObject:connection];
  138. }
  139. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  140. [self.connections removeObject:connection];
  141. }
  142. @end