RCTDataRequestHandler.mm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import <React/RCTDataRequestHandler.h>
  8. #import <ReactCommon/RCTTurboModule.h>
  9. #import "RCTNetworkPlugins.h"
  10. @interface RCTDataRequestHandler() <RCTTurboModule>
  11. @end
  12. @implementation RCTDataRequestHandler
  13. {
  14. NSOperationQueue *_queue;
  15. }
  16. RCT_EXPORT_MODULE()
  17. - (void)invalidate
  18. {
  19. [_queue cancelAllOperations];
  20. _queue = nil;
  21. }
  22. - (BOOL)canHandleRequest:(NSURLRequest *)request
  23. {
  24. return [request.URL.scheme caseInsensitiveCompare:@"data"] == NSOrderedSame;
  25. }
  26. - (NSOperation *)sendRequest:(NSURLRequest *)request
  27. withDelegate:(id<RCTURLRequestDelegate>)delegate
  28. {
  29. // Lazy setup
  30. if (!_queue) {
  31. _queue = [NSOperationQueue new];
  32. _queue.maxConcurrentOperationCount = 2;
  33. }
  34. __weak __block NSBlockOperation *weakOp;
  35. __block NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
  36. // Get mime type
  37. NSRange firstSemicolon = [request.URL.resourceSpecifier rangeOfString:@";"];
  38. NSString *mimeType = firstSemicolon.length ? [request.URL.resourceSpecifier substringToIndex:firstSemicolon.location] : nil;
  39. // Send response
  40. NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
  41. MIMEType:mimeType
  42. expectedContentLength:-1
  43. textEncodingName:nil];
  44. [delegate URLRequest:weakOp didReceiveResponse:response];
  45. // Load data
  46. NSError *error;
  47. NSData *data = [NSData dataWithContentsOfURL:request.URL
  48. options:NSDataReadingMappedIfSafe
  49. error:&error];
  50. if (data) {
  51. [delegate URLRequest:weakOp didReceiveData:data];
  52. }
  53. [delegate URLRequest:weakOp didCompleteWithError:error];
  54. }];
  55. weakOp = op;
  56. [_queue addOperation:op];
  57. return op;
  58. }
  59. - (void)cancelRequest:(NSOperation *)op
  60. {
  61. [op cancel];
  62. }
  63. @end
  64. Class RCTDataRequestHandlerCls(void) {
  65. return RCTDataRequestHandler.class;
  66. }