Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing request token for request: <NSURLRequest: 0x60000253e5a0> { URL: file:// #29364

Closed
sagarlava opened this issue Jul 14, 2020 · 113 comments
Closed
Labels
🌐Networking Related to a networking API. Platform: iOS iOS applications. Resolution: Fixed A PR that fixes this issue has been merged. Resolution: Locked This issue was locked by the bot. Resolution: PR Submitted A pull request with a fix has been provided.

Comments

@sagarlava
Copy link

sagarlava commented Jul 14, 2020

Description

I just upgraded to RN 0.63.0 and all fine, but only for upload using axios, i get

Missing request token for request: <NSURLRequest: 0x60000253e5a0> { URL: file:

image

React Native version:

System:
OS: macOS 10.15.5
CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
Memory: 163.19 MB / 8.00 GB
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.16.1 - /usr/local/bin/node
Yarn: 1.22.4 - /usr/local/bin/yarn
npm: 6.13.4 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
Managers:
CocoaPods: 1.9.1 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: iOS 13.4, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2
Android SDK:
API Levels: 22, 23, 25, 26, 27, 28, 29
Build Tools: 23.0.3, 27.0.3, 28.0.3, 29.0.0, 29.0.2
System Images: android-28 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-R | Google APIs Intel x86 Atom
Android NDK: Not Found
IDEs:
Android Studio: 4.0 AI-193.6911.18.40.6514223
Xcode: 11.4.1/11E503a - /usr/bin/xcodebuild
Languages:
Java: 1.8.0_221 - /usr/bin/javac
Python: 2.7.16 - /usr/bin/python
npmPackages:
@react-native-community/cli: Not Found
react: 16.13.1 => 16.13.1
react-native: 0.63.0 => 0.63.0
npmGlobalPackages:
react-native: Not Found

Steps To Reproduce

Here is my code snippet and that gives me error

  const cleanURL = body.imageData.uri.replace("file://", "");
  const data = new FormData();
  let fileName = body.imageData.fileName ? body.imageData.fileName : moment().unix()+'.jpg'
  data.append('file', {
    uri: cleanURL,
    name: fileName,
    type: body.imageData.type
  });
  data.append('fileName', fileName)
  return axiosclient.post(
    '/upload,
    data,
    {
      headers: {
        "content-type": "multipart/form-data"
      }
    }
  ).then(res => {
   
  }).catch(err => {
    
  })

Expected Results

Should upload file, it was fine in 0.62.2

@PaitoAnderson
Copy link
Contributor

Same issue with fetch for me when updating to 0.63.0.

@ramacatur
Copy link

Same issue with axios after update to 0.63.0

@YannDeck
Copy link

The issue is still here with 0.63.1, 100% reproducible on iOS. (tested with fetch and axios)
The problem seems to come from loadImageWithURLRequest as mentioned here

@struct78
Copy link

Here is a minimal repo that demonstrates this error. Choose a file from the camera roll and then try to retrieve that using fetch.

https://github.com/struct78/react-native-0.63.1-missing-request-token

@helderberto
Copy link

helderberto commented Jul 16, 2020

Same issue with axios after update to 0.63.1.

This problem only happens on the iOS (simulator/device).

Related issues:
#28551
#29021

@caiangums
Copy link

Hey, I caught up @helderburato and we tried some approaches. This seems an error not much related to token, even the error sending this message.

TL;DR: We do not manage to correct the issue. But we made some research, discovered something about it, created assumptions but for now, we are downgrading the version of our RN lib to 0.61.4. Here is what we managed to discover! 😄

Some steps to catch what we accomplish:

  • Added some logs at RCTNetworkTask.mm, method start():
- (void)start
{
  if (_status != RCTNetworkTaskPending) {
    RCTLogError(@"RCTNetworkTask was already started or completed");
    return;
  }

  if (_requestToken == nil) {
    id token = [_handler sendRequest:_request withDelegate:self];

    RCTLog(@"token %@", token); // <- here
    RCTLog(@"_handler %@", _handler); // <- here
    if ([self validateRequestToken:token]) {
      _selfReference = self;
      _status = RCTNetworkTaskInProgress;
    }
  }
}
  • Added some logs at RCTNetworkTask.mm, method validateRequestToken():
- (BOOL)validateRequestToken:(id)requestToken
{
  BOOL valid = YES;
  if (_requestToken == nil) {
    if (requestToken == nil) {
      if (RCT_DEBUG) {
        RCTLog(@"error _handler %@", _handler); // <- here
        RCTLog(@"error requestToken %@", requestToken); // <- here
        RCTLogError(@"Missing request token for request: %@", _request);
      }
      valid = NO;
    }
    _requestToken = requestToken;
  } else if (![requestToken isEqual:_requestToken]) {
    if (RCT_DEBUG) {
      RCTLogError(@"Unrecognized request token: %@ expected: %@", requestToken, _requestToken);
    }
    valid = NO;
  }
  /* ... */
}

Then I identified an issue with RCTImageLoader on calling the method sendRequest(). Then I went across the implementation inside the RCTImageLoader.mm file and added some logs inside of it. After discussing with an iOS developer friend (@Cherobin) that knows how Obj-C works, we created the assumption of the problem being the callback from requestToken not being fulfilled resulting in token being nil (null). This maybe happens because of how quick the code executes in comparison of how slow the callback is executed based on image size. We are reducing the image size with a JS lib before sending requests, so this happens with even a small size of images.

We tried to use a Semaphore but it seems not to resolve the issue. At the file RCTImageLoader we created some logs at sendRequest() and the following code is what we produced:

- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
{
  // create the semaphore
  dispatch_semaphore_t sema = dispatch_semaphore_create(0);

  __block RCTImageLoaderCancellationBlock requestToken;
  requestToken = [self loadImageWithURLRequest:request callback:^(NSError *error, UIImage *image) {
    RCTLog(@"error %@", error); // <- log here
    if (error) {
      [delegate URLRequest:requestToken didCompleteWithError:error];
      return;
    }

    NSString *mimeType = nil;
    NSData *imageData = nil;
    if (RCTImageHasAlpha(image.CGImage)) {
      mimeType = @"image/png";
      imageData = UIImagePNGRepresentation(image);
    } else {
      mimeType = @"image/jpeg";
      imageData = UIImageJPEGRepresentation(image, 1.0);
    }
    RCTLog(@"mimeType %@", mimeType); // <- log here
    RCTLog(@"imageData %@", imageData); // <- log here

    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
                                                        MIMEType:mimeType
                                           expectedContentLength:imageData.length
                                                textEncodingName:nil];
    RCTLog(@"response %@", response); // <- log here

    [delegate URLRequest:requestToken didReceiveResponse:response];
    [delegate URLRequest:requestToken didReceiveData:imageData];
    [delegate URLRequest:requestToken didCompleteWithError:nil];
    RCTLog(@"delegate %@", delegate); // <- log here

    // Release the semaphore
    dispatch_semaphore_signal(sema);
  }];

  // Here we lock until the semaphore release
  if (![NSThread isMainThread]) {
      dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  } else {
      while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) {
          [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
      }
  }

  RCTLog(@"RCTImageLoader requestToken %@", requestToken); // <- log here
  return requestToken;
}

Hope that helps someone! 😄

@uusa35
Copy link

uusa35 commented Jul 19, 2020

Simulator Screen Shot - iPhone Xʀ - 2020-07-20 at 01 25 28

i have the same issue RN 0.63.1
any updates ? !

it was just working fine before i upgrade to 0.63

Screen Shot 2020-07-20 at 1 28 54 AM

@uusa35
Copy link

uusa35 commented Jul 21, 2020

fixed the error

before i was fetching image.path and it was working just fine.

now u have to pass the sourceURL as the following

Screen Shot 2020-07-21 at 8 12 17 AM

@jamesshaw49
Copy link

jamesshaw49 commented Jul 21, 2020

fixed the error

before i was fetching image.path and it was working just fine.

now u have to pass the sourceURL as the following

Screen Shot 2020-07-21 at 8 12 17 AM

Interesting. However, this doesn't seem to have fixed it for me. Problem is only present on the simulator, no issue on an actual device. In addition, my simulator also freezes after accessing the image and requires a restart.

@caiangums
Copy link

fixed the error

before i was fetching image.path and it was working just fine.

now u have to pass the sourceURL as the following

Screen Shot 2020-07-21 at 8 12 17 AM

Hey! Can you tell more about how you did it and deliver an example to reproduce it?

@jamesshaw49
Copy link

jamesshaw49 commented Jul 21, 2020

fixed the error
before i was fetching image.path and it was working just fine.
now u have to pass the sourceURL as the following
Screen Shot 2020-07-21 at 8 12 17 AM

Hey! Can you tell more about how you did it and deliver an example to reproduce it?

Hi @caiangums, I actually thought it may be related to the library I was using, so I posted more detail about this issue on their repo. Check it out here: ivpusic/react-native-image-crop-picker#1348

Finally, I remember a strange bug I once had with Android when posting images to the server. It turned out to be related to the Flipper version (#28551). I have tried disabling Flipper totally in RN 63, but this has not solved our issue. However, I thought I would mention it incase those more knowledgable about RN could find a link between the two issues.

@anthony1110
Copy link

I also have same issue. I use hack for this #29021 (comment).

@caiangums
Copy link

Hi @anthony1110! Thanks for mentioning it.

I think your solution is a bad approach. Instead of correcting the issue, you avoided an error and considered valid.

@anthony1110
Copy link

anthony1110 commented Jul 22, 2020

@caiangums , yup, that hack is a bad method, just a temporary hack to make it working. Still require react-native developer to provide a real fix for this issue.

@caiangums
Copy link

Good point @anthony1110! I think we all made some progress with our knowledge and maybe when someone from the RN team comes here they will have some ground on where to start.

btw does your "hack" generated side-effects? Did you notice something? 🤔

@uusa35
Copy link

uusa35 commented Jul 23, 2020

fixed the error
before i was fetching image.path and it was working just fine.
now u have to pass the sourceURL as the following
Screen Shot 2020-07-21 at 8 12 17 AM

Hey! Can you tell more about how you did it and deliver an example to reproduce it?

find the comment below
#29364 (comment)

also i can confirm that my solution worked on ios but not on android. so weird

@SocialBrothersDEV
Copy link

Same issue here on 0.63

@anthony1110
Copy link

Good point @anthony1110! I think we all made some progress with our knowledge and maybe when someone from the RN team comes here they will have some ground on where to start.

btw does your "hack" generated side-effects? Did you notice something? 🤔

@caiangums , so far so good from my application to upload and download image with the hack. Again, it is still bad hack, still need to wait react-native developer to fix it. Also, I believe upgrade Flipper version will fix the issue but I am not sure how to upgrade Flipper version in IOS/podfile.

@caiangums
Copy link

fixed the error
before i was fetching image.path and it was working just fine.
now u have to pass the sourceURL as the following
Screen Shot 2020-07-21 at 8 12 17 AM

Hey! Can you tell more about how you did it and deliver an example to reproduce it?

find the comment below
#29364 (comment)

also i can confirm that my solution worked on ios but not on android. so weird

Hey @uusa35, thanks for your reply. My request is for an example to reproduce. As far as I can see, your comment just has some prints from your code and it was traced that the issue may be related to some bug inside the Objective-C RN lib.

Just to be clear:

  • "Works on my machine" is not a good reply in any case (I tested your solution on my code and still not work)
  • "An example to reproduce it" by far is not prints from your code. @struct78 gave an example with a repo and this is a real example to reproduce it
  • The thread has some other information about it. If possible, maybe you can check it out. As an example, @anthony1110 found a way to avoid the issue modifying the RN source code directly and it worked but he already said this is a "hack" and is better to wait until someone from RN team(or anyone with more knowledge in Obj-C background) catch-up and fix the issue

@ajanauskas
Copy link

The main issue like someone mentioned is within RCTImageLoader.mm implementation:

- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
{
  __block RCTImageLoaderCancellationBlock requestToken;
  requestToken = [self loadImageWithURLRequest:request callback:^(NSError *error, UIImage *image) {
    if (error) {
      [delegate URLRequest:requestToken didCompleteWithError:error];
      return;
    }

    NSString *mimeType = nil;
    NSData *imageData = nil;
    if (RCTImageHasAlpha(image.CGImage)) {
      mimeType = @"image/png";
      imageData = UIImagePNGRepresentation(image);
    } else {
      mimeType = @"image/jpeg";
      imageData = UIImageJPEGRepresentation(image, 1.0);
    }

    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
                                                        MIMEType:mimeType
                                           expectedContentLength:imageData.length
                                                textEncodingName:nil];

    [delegate URLRequest:requestToken didReceiveResponse:response];
    [delegate URLRequest:requestToken didReceiveData:imageData];
    [delegate URLRequest:requestToken didCompleteWithError:nil];
  }];

  return requestToken;
}

Error is thrown out because requestToken is nil. Like someone else has pointed out it is nil because completionBlock executes before requestToken is initialised. It happens because some image loader is performing task synchronously.

I've managed to fix issue for my project by reverting this commit: 3198009#diff-9a034658197479288c4d346a0eb4d98c

@dan-lee
Copy link

dan-lee commented Jul 23, 2020

@ajanauskas Looks promising, but unfortunately it didn't change anything for me.

My patch looks like this
diff --git a/node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm b/node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm
index 8669ad3..7a55058 100644
--- a/node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm
+++ b/node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm
@@ -49,19 +49,28 @@ - (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
                                  partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
                                   completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
 {
-  UIImage *image = RCTImageFromLocalAssetURL(imageURL);
-  if (image) {
-    if (progressHandler) {
-      progressHandler(1, 1);
+  __block auto cancelled = std::make_shared<std::atomic<bool>>(false);
+  RCTExecuteOnMainQueue(^{
+    if (cancelled->load()) {
+      return;
     }
-    completionHandler(nil, image);
-  } else {
-    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
-    RCTLogWarn(@"%@", message);
-    completionHandler(RCTErrorWithMessage(message), nil);
-  }

-  return nil;
+    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
+    if (image) {
+      if (progressHandler) {
+        progressHandler(1, 1);
+      }
+      completionHandler(nil, image);
+    } else {
+      NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
+      RCTLogWarn(@"%@", message);
+      completionHandler(RCTErrorWithMessage(message), nil);
+    }
+  });
+
+  return ^{
+    cancelled->store(true);
+  };
 }

 @end

Is that all that needs to be done?

@anthony1110
Copy link

I tested @ajanauskas fix and it is working. Thanks @ajanauskas !

@keithhackbarth

This comment has been minimized.

@awinograd
Copy link
Contributor

@keithhackbarth The original issue and error information added to this issue seems pretty iOS specific. If you're seeing something similar on android i'd suggest opening a separate issue.

@keithhackbarth
Copy link

Sorry @awinograd . Looks like a more generic discussion is happening on #29021 I'll move my comment over there.

@joaoschaab
Copy link

any update on this ?

@devkrkanhaiya
Copy link

devkrkanhaiya commented Sep 18, 2020

in
node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm file

Replace Below

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }

return nil;
}

With

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    __block auto cancelled = std::make_shared<std::atomic>(false);
    RCTExecuteOnMainQueue(^{
    if (cancelled->load()) {
    return;
    }

    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }
    });

    return ^{
    cancelled->store(true);
    };
    }

This..

Like and Love , if it work 👍

@fahelmoreira
Copy link

fahelmoreira commented Sep 19, 2020

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

It only works for the real device, on simulator still give the error but at least you can deploy your app until this issue is patched

@patrick-agency73
Copy link

patrick-agency73 commented Sep 22, 2020

For now

npm i react-native@0.0.0-c3ab2a254 --save

If you want to lock a version (using latest nightly),
but the podspecs are broken so you'll have to edit

moishe-mobile-v2/node_modules/react-native/package.json

and change the version to "6.3.2" to be be able to install the pods until the make a fix for the nightlies.

Or if you want the latest build without any locking

npm i facebook/react-native.git#master --save

which the Podspecs dont break, but youre at the mercy of new bugs obviously each time you build.
In my opinion these are the only two correct solutions, instead of trying to hack pieces of the package

@hellotrei
Copy link

For now
npm i react-native@0.0.0-949dedca9 --save

is that work?

@safaiyeh
Copy link
Contributor

For now

npm i react-native@0.0.0-949dedca9 --save

is that work?

Yeah there are nightly builds.

@anastely
Copy link

@onebotforyou Don't forget to delete Pods and run npx pod-install again ;)

@Jonatthu
Copy link

@fahelmoreira it works for me on real device thanks!

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

It only works for the real device, on simulator still give the error but at lease foi can deploy you app until this issue is patched

@fdkitlui
Copy link

fdkitlui commented Sep 25, 2020

I also have same issue. I use hack for this #29021 (comment).

Nice temporary hack! It works in RN 0.63.2
I think we can do one more step.

copy the hacked RCTNetworkTask.mm into ios folder.
create a script 'runThisPodInstall.sh' in ios folder with these content:

#!/bin/sh
rm -rf *.xcworkspace
rm -rf Pods/
cp -f RCTNetworkTask.mm ../node_modules/react-native/Libraries/Network/
pod install

chmod +x runThisPodInstall.sh
everytime we remove the node_modules, wait for yarn install to be done, cd ios and ./runThisPodInstall.sh

@karanmartian
Copy link

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

It only works for the real device, on simulator still give the error but at least you can deploy your app until this issue is patched

Beautiful it works, but can you explain the logic for this? What's private supposed to do?

@joealba
Copy link

joealba commented Sep 29, 2020

React Native 0.63.3 is available now. And in my local testing, this issue is now resolved. Thanks so much, all!

@karanmartian
Copy link

Great! But is it available in the Expo RN version?

@safaiyeh
Copy link
Contributor

Glad the fix made it!

@sagarlava
Copy link
Author

Good job.. thanks a lot

@phillipkey
Copy link

Can also confirm that with RN 63.3 I am no longer seeing the issue.

@honzajerabek
Copy link

upload form data image with axios fixed with v0.63.3

@EmersonGarrido
Copy link

v0.63.3 axio / expo and react native i am still having problem request token in the upload of image formData IOS

@AliUZAR
Copy link

AliUZAR commented Oct 14, 2020

Same issue on v0.63.2
npx react-native upgrade upgraded to v0.63.3 fixed the error.

@NathanNovak
Copy link

Same issue on v0.63.2
npx react-native upgrade upgraded to v0.63.3 fixed the error.

@AliUZAR This worked for me.

@Balasnest
Copy link

Balasnest commented Nov 3, 2020

@joealba getting this build error after upgrade from 0.63.2 to 0.63.3.

npm ERR! code EINTEGRITY
npm ERR! Verification failed while extracting jsc-android@241213.1.0:
npm ERR! Verification failed while extracting jsc-android@241213.1.0:
npm ERR! sha512-AH8NYyMNLNhcUEF97QbMxPNLNW+oiSBlvm1rsMNzgJ1d5TQzdh/AOJGsxeeESp3m9YIWGLCgUvGTVoVLs0p68A== integrity checksum failed when using sha512: wanted sha512-AH8NYyMNLNhcUEF97QbMxPNLNW+oiSBlvm1rsMNzgJ1d5TQzdh/AOJGsxeeESp3m9YIWGLCgUvGTVoVLs0p68A== but got sha512-ptI+efRlVdodigsznoyx5zuvQcHCk3NgWkC8GR/qr2pRl87wCpMDqzDs/zvKfm3zkBALvOaF2E/gD5DePG4G4Q==. (4273248 bytes)

Any idea?

@GuilhermeTrivilin
Copy link

Error fixed when updating React Native to version 0.63.3

@namxg6626
Copy link

Same issue on v0.63.2
npx react-native upgrade upgraded to v0.63.3 fixed the error.

it worked. thanks

@teachdugsimt
Copy link

  1. go : node_modules/react-native/Libraries/image
    replace following.
    /*
  • Copyright (c) Facebook, Inc. and its affiliates.
  • This source code is licensed under the MIT license found in the
  • LICENSE file in the root directory of this source tree.
    */

#import <React/RCTLocalAssetImageLoader.h>

#import
#import

#import <React/RCTUtils.h>
#import <ReactCommon/RCTTurboModule.h>

#import "RCTImagePlugins.h"

@interface RCTLocalAssetImageLoader()
@EnD

@implementation RCTLocalAssetImageLoader

RCT_EXPORT_MODULE()

  • (BOOL)canLoadImageURL:(NSURL *)requestURL
    {
    return RCTIsLocalAssetURL(requestURL);
    }

  • (BOOL)requiresScheduling
    {
    // Don't schedule this loader on the URL queue so we can load the
    // local assets synchronously to avoid flickers.
    return NO;
    }

  • (BOOL)shouldCacheLoadedImages
    {
    // UIImage imageNamed handles the caching automatically so we don't want
    // to add it to the image cache.
    return NO;
    }

  • (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    __block auto cancelled = std::make_shared<std::atomic>(false);
    RCTExecuteOnMainQueue(^{
    if (cancelled->load()) {
    return;
    }
    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }
    });

return ^{
cancelled->store(true);
};
}

@EnD

Class RCTLocalAssetImageLoaderCls(void) {
return RCTLocalAssetImageLoader.class;
}

  1. build formData like this
    let formData = new FormData();
    formData.append("file", {
    name:file.fileName,
    uri: Platform.OS == 'ios' ? file.uri.replace("file://", "") : file.uri,
    type: file.type,
    width: file.width,
    size: file.fileSize
    })

** rn version : 0.63+

@lfoliveir4
Copy link

React Native 0.63.3 is available now. And in my local testing, this issue is now resolved. Thanks so much, all!

I had this same problem in 0.62.2 Only the update to version 0.63.3 solved the problem.

Update link: https://react-native-community.github.io/upgrade-helper/?from=0.63.2&to=0.63.3

@victorglomer
Copy link

in my mac I needed to do like this (without "/private"):

 const data = new FormData();
    data.append("avatar", {
      type: "image/jpeg",
      name: `${user.id}.jpg`,
      uri:
        Platform.OS == "ios"
          ? response.uri?.replace("file://", "/")
          : response.uri,
    });

@facebook facebook locked as resolved and limited conversation to collaborators Oct 1, 2021
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Oct 1, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
🌐Networking Related to a networking API. Platform: iOS iOS applications. Resolution: Fixed A PR that fixes this issue has been merged. Resolution: Locked This issue was locked by the bot. Resolution: PR Submitted A pull request with a fix has been provided.
Projects
None yet
Development

Successfully merging a pull request may close this issue.