mirror of
https://github.com/zhigang1992/react-native.git
synced 2026-04-29 12:45:37 +08:00
Make FBReactModule, RCTNetworking, and RCTImageLoader use new Plugin API
Summary: This diff wires up everything from the previous 8 diffs. After this, all codepaths that execute `modulesConformingToProtocol` in `RCTImageLoader.m` will instead use iOS plugins to retrieve the modules on FBiOS. Reviewed By: fkgozali Differential Revision: D14360252 fbshipit-source-id: 6f0cecfa8dffa1955ba2f9ed54bc1c130fb23341
This commit is contained in:
committed by
Facebook Github Bot
parent
0090ab32c2
commit
b8f9932883
@@ -16,6 +16,9 @@ typedef void (^RCTImageLoaderPartialLoadBlock)(UIImage *image);
|
|||||||
typedef void (^RCTImageLoaderCompletionBlock)(NSError *error, UIImage *image);
|
typedef void (^RCTImageLoaderCompletionBlock)(NSError *error, UIImage *image);
|
||||||
typedef dispatch_block_t RCTImageLoaderCancellationBlock;
|
typedef dispatch_block_t RCTImageLoaderCancellationBlock;
|
||||||
|
|
||||||
|
@protocol RCTImageURLLoader;
|
||||||
|
@protocol RCTImageDataDecoder;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provides an interface to use for providing a image caching strategy.
|
* Provides an interface to use for providing a image caching strategy.
|
||||||
*/
|
*/
|
||||||
@@ -87,6 +90,9 @@ typedef dispatch_block_t RCTImageLoaderCancellationBlock;
|
|||||||
|
|
||||||
- (instancetype)init;
|
- (instancetype)init;
|
||||||
- (instancetype)initWithRedirectDelegate:(id<RCTImageRedirectProtocol>)redirectDelegate NS_DESIGNATED_INITIALIZER;
|
- (instancetype)initWithRedirectDelegate:(id<RCTImageRedirectProtocol>)redirectDelegate NS_DESIGNATED_INITIALIZER;
|
||||||
|
- (instancetype)initWithRedirectDelegate:(id<RCTImageRedirectProtocol>)redirectDelegate
|
||||||
|
loadersProvider:(NSArray<id<RCTImageURLLoader>> * (^)(void))getLoaders
|
||||||
|
decodersProvider:(NSArray<id<RCTImageDataDecoder>> * (^)(void))getDecoders;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads the specified image at the highest available resolution.
|
* Loads the specified image at the highest available resolution.
|
||||||
|
|||||||
@@ -61,6 +61,8 @@ static NSInteger RCTImageBytesForImage(UIImage *image)
|
|||||||
|
|
||||||
@implementation RCTImageLoader
|
@implementation RCTImageLoader
|
||||||
{
|
{
|
||||||
|
NSArray<id<RCTImageURLLoader>> * (^_loadersProvider)(void);
|
||||||
|
NSArray<id<RCTImageDataDecoder>> * (^_decodersProvider)(void);
|
||||||
NSArray<id<RCTImageURLLoader>> *_loaders;
|
NSArray<id<RCTImageURLLoader>> *_loaders;
|
||||||
NSArray<id<RCTImageDataDecoder>> *_decoders;
|
NSArray<id<RCTImageDataDecoder>> *_decoders;
|
||||||
NSOperationQueue *_imageDecodeQueue;
|
NSOperationQueue *_imageDecodeQueue;
|
||||||
@@ -96,13 +98,24 @@ RCT_EXPORT_MODULE()
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
- (instancetype)initWithRedirectDelegate:(id<RCTImageRedirectProtocol>)redirectDelegate
|
||||||
|
loadersProvider:(NSArray<id<RCTImageURLLoader>> * (^)(void))getLoaders
|
||||||
|
decodersProvider:(NSArray<id<RCTImageDataDecoder>> * (^)(void))getHandlers
|
||||||
|
{
|
||||||
|
if (self = [self initWithRedirectDelegate:redirectDelegate]) {
|
||||||
|
_loadersProvider = getLoaders;
|
||||||
|
_decodersProvider = getHandlers;
|
||||||
|
}
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
|
||||||
- (void)setUp
|
- (void)setUp
|
||||||
{
|
{
|
||||||
// Set defaults
|
// Set defaults
|
||||||
_maxConcurrentLoadingTasks = _maxConcurrentLoadingTasks ?: 4;
|
_maxConcurrentLoadingTasks = _maxConcurrentLoadingTasks ?: 4;
|
||||||
_maxConcurrentDecodingTasks = _maxConcurrentDecodingTasks ?: 2;
|
_maxConcurrentDecodingTasks = _maxConcurrentDecodingTasks ?: 2;
|
||||||
_maxConcurrentDecodingBytes = _maxConcurrentDecodingBytes ?: 30 * 1024 * 1024; // 30MB
|
_maxConcurrentDecodingBytes = _maxConcurrentDecodingBytes ?: 30 * 1024 * 1024; // 30MB
|
||||||
|
|
||||||
_URLRequestQueue = dispatch_queue_create("com.facebook.react.ImageLoaderURLRequestQueue", DISPATCH_QUEUE_SERIAL);
|
_URLRequestQueue = dispatch_queue_create("com.facebook.react.ImageLoaderURLRequestQueue", DISPATCH_QUEUE_SERIAL);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,11 +146,18 @@ RCT_EXPORT_MODULE()
|
|||||||
if (!_maxConcurrentLoadingTasks) {
|
if (!_maxConcurrentLoadingTasks) {
|
||||||
[self setUp];
|
[self setUp];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!_loaders) {
|
if (!_loaders) {
|
||||||
// Get loaders, sorted in reverse priority order (highest priority first)
|
// Get loaders, sorted in reverse priority order (highest priority first)
|
||||||
RCTAssert(_bridge, @"Bridge not set");
|
RCTAssert(_bridge, @"Bridge not set");
|
||||||
_loaders = [[_bridge modulesConformingToProtocol:@protocol(RCTImageURLLoader)] sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageURLLoader> a, id<RCTImageURLLoader> b) {
|
|
||||||
|
if (_loadersProvider) {
|
||||||
|
_loaders = _loadersProvider();
|
||||||
|
} else {
|
||||||
|
_loaders = [_bridge modulesConformingToProtocol:@protocol(RCTImageURLLoader)];
|
||||||
|
}
|
||||||
|
|
||||||
|
_loaders = [_loaders sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageURLLoader> a, id<RCTImageURLLoader> b) {
|
||||||
float priorityA = [a respondsToSelector:@selector(loaderPriority)] ? [a loaderPriority] : 0;
|
float priorityA = [a respondsToSelector:@selector(loaderPriority)] ? [a loaderPriority] : 0;
|
||||||
float priorityB = [b respondsToSelector:@selector(loaderPriority)] ? [b loaderPriority] : 0;
|
float priorityB = [b respondsToSelector:@selector(loaderPriority)] ? [b loaderPriority] : 0;
|
||||||
if (priorityA > priorityB) {
|
if (priorityA > priorityB) {
|
||||||
@@ -149,7 +169,7 @@ RCT_EXPORT_MODULE()
|
|||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RCT_DEBUG) {
|
if (RCT_DEBUG) {
|
||||||
// Check for handler conflicts
|
// Check for handler conflicts
|
||||||
float previousPriority = 0;
|
float previousPriority = 0;
|
||||||
@@ -175,7 +195,7 @@ RCT_EXPORT_MODULE()
|
|||||||
}
|
}
|
||||||
return previousLoader;
|
return previousLoader;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normal code path
|
// Normal code path
|
||||||
for (id<RCTImageURLLoader> loader in _loaders) {
|
for (id<RCTImageURLLoader> loader in _loaders) {
|
||||||
if ([loader canLoadImageURL:URL]) {
|
if ([loader canLoadImageURL:URL]) {
|
||||||
@@ -190,10 +210,17 @@ RCT_EXPORT_MODULE()
|
|||||||
if (!_maxConcurrentLoadingTasks) {
|
if (!_maxConcurrentLoadingTasks) {
|
||||||
[self setUp];
|
[self setUp];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!_decoders) {
|
if (!_decoders) {
|
||||||
// Get decoders, sorted in reverse priority order (highest priority first)
|
// Get decoders, sorted in reverse priority order (highest priority first)
|
||||||
RCTAssert(_bridge, @"Bridge not set");
|
RCTAssert(_bridge, @"Bridge not set");
|
||||||
|
|
||||||
|
if (_decodersProvider) {
|
||||||
|
_decoders = _decodersProvider();
|
||||||
|
} else {
|
||||||
|
_decoders = [_bridge modulesConformingToProtocol:@protocol(RCTImageDataDecoder)];
|
||||||
|
}
|
||||||
|
|
||||||
_decoders = [[_bridge modulesConformingToProtocol:@protocol(RCTImageDataDecoder)] sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageDataDecoder> a, id<RCTImageDataDecoder> b) {
|
_decoders = [[_bridge modulesConformingToProtocol:@protocol(RCTImageDataDecoder)] sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageDataDecoder> a, id<RCTImageDataDecoder> b) {
|
||||||
float priorityA = [a respondsToSelector:@selector(decoderPriority)] ? [a decoderPriority] : 0;
|
float priorityA = [a respondsToSelector:@selector(decoderPriority)] ? [a decoderPriority] : 0;
|
||||||
float priorityB = [b respondsToSelector:@selector(decoderPriority)] ? [b decoderPriority] : 0;
|
float priorityB = [b respondsToSelector:@selector(decoderPriority)] ? [b decoderPriority] : 0;
|
||||||
@@ -206,7 +233,7 @@ RCT_EXPORT_MODULE()
|
|||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RCT_DEBUG) {
|
if (RCT_DEBUG) {
|
||||||
// Check for handler conflicts
|
// Check for handler conflicts
|
||||||
float previousPriority = 0;
|
float previousPriority = 0;
|
||||||
@@ -233,7 +260,7 @@ RCT_EXPORT_MODULE()
|
|||||||
}
|
}
|
||||||
return previousDecoder;
|
return previousDecoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normal code path
|
// Normal code path
|
||||||
for (id<RCTImageDataDecoder> decoder in _decoders) {
|
for (id<RCTImageDataDecoder> decoder in _decoders) {
|
||||||
if ([decoder canDecodeImageData:data]) {
|
if ([decoder canDecodeImageData:data]) {
|
||||||
@@ -304,11 +331,11 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tasksToRemove) {
|
if (tasksToRemove) {
|
||||||
[self->_pendingTasks removeObjectsInArray:tasksToRemove];
|
[self->_pendingTasks removeObjectsInArray:tasksToRemove];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start queued decode
|
// Start queued decode
|
||||||
NSInteger activeDecodes = self->_scheduledDecodes - self->_pendingDecodes.count;
|
NSInteger activeDecodes = self->_scheduledDecodes - self->_pendingDecodes.count;
|
||||||
while (activeDecodes == 0 || (self->_activeBytes <= self->_maxConcurrentDecodingBytes &&
|
while (activeDecodes == 0 || (self->_activeBytes <= self->_maxConcurrentDecodingBytes &&
|
||||||
@@ -321,7 +348,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start queued tasks
|
// Start queued tasks
|
||||||
for (RCTNetworkTask *task in self->_pendingTasks) {
|
for (RCTNetworkTask *task in self->_pendingTasks) {
|
||||||
if (MAX(self->_activeTasks, self->_scheduledDecodes) >= self->_maxConcurrentLoadingTasks) {
|
if (MAX(self->_activeTasks, self->_scheduledDecodes) >= self->_maxConcurrentLoadingTasks) {
|
||||||
@@ -353,7 +380,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[NSURLProtocol setProperty:@"RCTImageLoader"
|
[NSURLProtocol setProperty:@"RCTImageLoader"
|
||||||
forKey:@"trackingName"
|
forKey:@"trackingName"
|
||||||
inRequest:mutableRequest];
|
inRequest:mutableRequest];
|
||||||
|
|
||||||
// Add missing png extension
|
// Add missing png extension
|
||||||
if (request.URL.fileURL && request.URL.pathExtension.length == 0) {
|
if (request.URL.fileURL && request.URL.pathExtension.length == 0) {
|
||||||
mutableRequest.URL = [request.URL URLByAppendingPathExtension:@"png"];
|
mutableRequest.URL = [request.URL URLByAppendingPathExtension:@"png"];
|
||||||
@@ -363,15 +390,15 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
}
|
}
|
||||||
request = mutableRequest;
|
request = mutableRequest;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find suitable image URL loader
|
// Find suitable image URL loader
|
||||||
id<RCTImageURLLoader> loadHandler = [self imageURLLoaderForURL:request.URL];
|
id<RCTImageURLLoader> loadHandler = [self imageURLLoaderForURL:request.URL];
|
||||||
BOOL requiresScheduling = [loadHandler respondsToSelector:@selector(requiresScheduling)] ?
|
BOOL requiresScheduling = [loadHandler respondsToSelector:@selector(requiresScheduling)] ?
|
||||||
[loadHandler requiresScheduling] : YES;
|
[loadHandler requiresScheduling] : YES;
|
||||||
|
|
||||||
BOOL cacheResult = [loadHandler respondsToSelector:@selector(shouldCacheLoadedImages)] ?
|
BOOL cacheResult = [loadHandler respondsToSelector:@selector(shouldCacheLoadedImages)] ?
|
||||||
[loadHandler shouldCacheLoadedImages] : YES;
|
[loadHandler shouldCacheLoadedImages] : YES;
|
||||||
|
|
||||||
__block atomic_bool cancelled = ATOMIC_VAR_INIT(NO);
|
__block atomic_bool cancelled = ATOMIC_VAR_INIT(NO);
|
||||||
__block dispatch_block_t cancelLoad = nil;
|
__block dispatch_block_t cancelLoad = nil;
|
||||||
__block NSLock *cancelLoadLock = [NSLock new];
|
__block NSLock *cancelLoadLock = [NSLock new];
|
||||||
@@ -379,7 +406,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[cancelLoadLock lock];
|
[cancelLoadLock lock];
|
||||||
cancelLoad = nil;
|
cancelLoad = nil;
|
||||||
[cancelLoadLock unlock];
|
[cancelLoadLock unlock];
|
||||||
|
|
||||||
// If we've received an image, we should try to set it synchronously,
|
// If we've received an image, we should try to set it synchronously,
|
||||||
// if it's data, do decoding on a background thread.
|
// if it's data, do decoding on a background thread.
|
||||||
if (RCTIsMainQueue() && ![imageOrData isKindOfClass:[UIImage class]]) {
|
if (RCTIsMainQueue() && ![imageOrData isKindOfClass:[UIImage class]]) {
|
||||||
@@ -394,7 +421,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionBlock(error, imageOrData, cacheResult, response);
|
completionBlock(error, imageOrData, cacheResult, response);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// If the loader doesn't require scheduling we call it directly on
|
// If the loader doesn't require scheduling we call it directly on
|
||||||
// the main queue.
|
// the main queue.
|
||||||
if (loadHandler && !requiresScheduling) {
|
if (loadHandler && !requiresScheduling) {
|
||||||
@@ -408,19 +435,19 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionHandler(error, image, nil);
|
completionHandler(error, image, nil);
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
// All access to URL cache must be serialized
|
// All access to URL cache must be serialized
|
||||||
if (!_URLRequestQueue) {
|
if (!_URLRequestQueue) {
|
||||||
[self setUp];
|
[self setUp];
|
||||||
}
|
}
|
||||||
|
|
||||||
__weak RCTImageLoader *weakSelf = self;
|
__weak RCTImageLoader *weakSelf = self;
|
||||||
dispatch_async(_URLRequestQueue, ^{
|
dispatch_async(_URLRequestQueue, ^{
|
||||||
__typeof(self) strongSelf = weakSelf;
|
__typeof(self) strongSelf = weakSelf;
|
||||||
if (atomic_load(&cancelled) || !strongSelf) {
|
if (atomic_load(&cancelled) || !strongSelf) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loadHandler) {
|
if (loadHandler) {
|
||||||
dispatch_block_t cancelLoadLocal = [loadHandler loadImageForURL:request.URL
|
dispatch_block_t cancelLoadLocal = [loadHandler loadImageForURL:request.URL
|
||||||
size:size
|
size:size
|
||||||
@@ -442,7 +469,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
scale:scale
|
scale:scale
|
||||||
resizeMode:resizeMode];
|
resizeMode:resizeMode];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (image) {
|
if (image) {
|
||||||
completionHandler(nil, image, nil);
|
completionHandler(nil, image, nil);
|
||||||
} else {
|
} else {
|
||||||
@@ -456,7 +483,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return ^{
|
return ^{
|
||||||
BOOL alreadyCancelled = atomic_fetch_or(&cancelled, 1);
|
BOOL alreadyCancelled = atomic_fetch_or(&cancelled, 1);
|
||||||
if (alreadyCancelled) {
|
if (alreadyCancelled) {
|
||||||
@@ -483,15 +510,15 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
request.URL.absoluteString);
|
request.URL.absoluteString);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
RCTNetworking *networking = [_bridge networking];
|
RCTNetworking *networking = [_bridge networking];
|
||||||
|
|
||||||
// Check if networking module can load image
|
// Check if networking module can load image
|
||||||
if (RCT_DEBUG && ![networking canHandleRequest:request]) {
|
if (RCT_DEBUG && ![networking canHandleRequest:request]) {
|
||||||
RCTLogError(@"No suitable image URL loader found for %@", request.URL.absoluteString);
|
RCTLogError(@"No suitable image URL loader found for %@", request.URL.absoluteString);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use networking module to load image
|
// Use networking module to load image
|
||||||
RCTURLRequestCompletionBlock processResponse = ^(NSURLResponse *response, NSData *data, NSError *error) {
|
RCTURLRequestCompletionBlock processResponse = ^(NSURLResponse *response, NSData *data, NSError *error) {
|
||||||
// Check for system errors
|
// Check for system errors
|
||||||
@@ -505,7 +532,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionHandler(RCTErrorWithMessage(@"Unknown image download error"), nil, response);
|
completionHandler(RCTErrorWithMessage(@"Unknown image download error"), nil, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for http errors
|
// Check for http errors
|
||||||
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||||
NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
|
NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
|
||||||
@@ -518,11 +545,11 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call handler
|
// Call handler
|
||||||
completionHandler(nil, data, response);
|
completionHandler(nil, data, response);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Download image
|
// Download image
|
||||||
__weak __typeof(self) weakSelf = self;
|
__weak __typeof(self) weakSelf = self;
|
||||||
__block RCTNetworkTask *task =
|
__block RCTNetworkTask *task =
|
||||||
@@ -532,7 +559,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
if (!strongSelf) {
|
if (!strongSelf) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error || !response || !data) {
|
if (error || !response || !data) {
|
||||||
NSError *someError = nil;
|
NSError *someError = nil;
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -546,22 +573,22 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[strongSelf dequeueTasks];
|
[strongSelf dequeueTasks];
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(strongSelf->_URLRequestQueue, ^{
|
dispatch_async(strongSelf->_URLRequestQueue, ^{
|
||||||
// Process image data
|
// Process image data
|
||||||
processResponse(response, data, nil);
|
processResponse(response, data, nil);
|
||||||
|
|
||||||
// Prepare for next task
|
// Prepare for next task
|
||||||
[strongSelf dequeueTasks];
|
[strongSelf dequeueTasks];
|
||||||
});
|
});
|
||||||
}];
|
}];
|
||||||
|
|
||||||
task.downloadProgressBlock = ^(int64_t progress, int64_t total) {
|
task.downloadProgressBlock = ^(int64_t progress, int64_t total) {
|
||||||
if (progressHandler) {
|
if (progressHandler) {
|
||||||
progressHandler(progress, total);
|
progressHandler(progress, total);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (task) {
|
if (task) {
|
||||||
if (!_pendingTasks) {
|
if (!_pendingTasks) {
|
||||||
_pendingTasks = [NSMutableArray new];
|
_pendingTasks = [NSMutableArray new];
|
||||||
@@ -569,7 +596,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[_pendingTasks addObject:task];
|
[_pendingTasks addObject:task];
|
||||||
[self dequeueTasks];
|
[self dequeueTasks];
|
||||||
}
|
}
|
||||||
|
|
||||||
return ^{
|
return ^{
|
||||||
__typeof(self) strongSelf = weakSelf;
|
__typeof(self) strongSelf = weakSelf;
|
||||||
if (!strongSelf || !task) {
|
if (!strongSelf || !task) {
|
||||||
@@ -608,14 +635,14 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
cancelLoadLocal();
|
cancelLoadLocal();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
__weak RCTImageLoader *weakSelf = self;
|
__weak RCTImageLoader *weakSelf = self;
|
||||||
void (^completionHandler)(NSError *, id, BOOL, NSURLResponse *) = ^(NSError *error, id imageOrData, BOOL cacheResult, NSURLResponse *response) {
|
void (^completionHandler)(NSError *, id, BOOL, NSURLResponse *) = ^(NSError *error, id imageOrData, BOOL cacheResult, NSURLResponse *response) {
|
||||||
__typeof(self) strongSelf = weakSelf;
|
__typeof(self) strongSelf = weakSelf;
|
||||||
if (atomic_load(&cancelled) || !strongSelf) {
|
if (atomic_load(&cancelled) || !strongSelf) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!imageOrData || [imageOrData isKindOfClass:[UIImage class]]) {
|
if (!imageOrData || [imageOrData isKindOfClass:[UIImage class]]) {
|
||||||
[cancelLoadLock lock];
|
[cancelLoadLock lock];
|
||||||
cancelLoad = nil;
|
cancelLoad = nil;
|
||||||
@@ -623,7 +650,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionBlock(error, imageOrData);
|
completionBlock(error, imageOrData);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
RCTImageLoaderCompletionBlock decodeCompletionHandler = ^(NSError *error_, UIImage *image) {
|
RCTImageLoaderCompletionBlock decodeCompletionHandler = ^(NSError *error_, UIImage *image) {
|
||||||
if (cacheResult && image) {
|
if (cacheResult && image) {
|
||||||
// Store decoded image in cache
|
// Store decoded image in cache
|
||||||
@@ -649,7 +676,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
cancelLoad = cancelLoadLocal;
|
cancelLoad = cancelLoadLocal;
|
||||||
[cancelLoadLock unlock];
|
[cancelLoadLock unlock];
|
||||||
};
|
};
|
||||||
|
|
||||||
cancelLoad = [self _loadImageOrDataWithURLRequest:imageURLRequest
|
cancelLoad = [self _loadImageOrDataWithURLRequest:imageURLRequest
|
||||||
size:size
|
size:size
|
||||||
scale:scale
|
scale:scale
|
||||||
@@ -671,7 +698,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionBlock(RCTErrorWithMessage(@"No image data"), nil);
|
completionBlock(RCTErrorWithMessage(@"No image data"), nil);
|
||||||
return ^{};
|
return ^{};
|
||||||
}
|
}
|
||||||
|
|
||||||
__block atomic_bool cancelled = ATOMIC_VAR_INIT(NO);
|
__block atomic_bool cancelled = ATOMIC_VAR_INIT(NO);
|
||||||
void (^completionHandler)(NSError *, UIImage *) = ^(NSError *error, UIImage *image) {
|
void (^completionHandler)(NSError *, UIImage *) = ^(NSError *error, UIImage *image) {
|
||||||
if (RCTIsMainQueue()) {
|
if (RCTIsMainQueue()) {
|
||||||
@@ -686,7 +713,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionBlock(error, clipped ? RCTResizeImageIfNeeded(image, size, scale, resizeMode) : image);
|
completionBlock(error, clipped ? RCTResizeImageIfNeeded(image, size, scale, resizeMode) : image);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
id<RCTImageDataDecoder> imageDecoder = [self imageDataDecoderForData:data];
|
id<RCTImageDataDecoder> imageDecoder = [self imageDataDecoderForData:data];
|
||||||
if (imageDecoder) {
|
if (imageDecoder) {
|
||||||
return [imageDecoder decodeImageData:data
|
return [imageDecoder decodeImageData:data
|
||||||
@@ -698,17 +725,17 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
dispatch_block_t decodeBlock = ^{
|
dispatch_block_t decodeBlock = ^{
|
||||||
// Calculate the size, in bytes, that the decompressed image will require
|
// Calculate the size, in bytes, that the decompressed image will require
|
||||||
NSInteger decodedImageBytes = (size.width * scale) * (size.height * scale) * 4;
|
NSInteger decodedImageBytes = (size.width * scale) * (size.height * scale) * 4;
|
||||||
|
|
||||||
// Mark these bytes as in-use
|
// Mark these bytes as in-use
|
||||||
self->_activeBytes += decodedImageBytes;
|
self->_activeBytes += decodedImageBytes;
|
||||||
|
|
||||||
// Do actual decompression on a concurrent background queue
|
// Do actual decompression on a concurrent background queue
|
||||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
||||||
if (!atomic_load(&cancelled)) {
|
if (!atomic_load(&cancelled)) {
|
||||||
|
|
||||||
// Decompress the image data (this may be CPU and memory intensive)
|
// Decompress the image data (this may be CPU and memory intensive)
|
||||||
UIImage *image = RCTDecodeImageWithData(data, size, scale, resizeMode);
|
UIImage *image = RCTDecodeImageWithData(data, size, scale, resizeMode);
|
||||||
|
|
||||||
#if RCT_DEV
|
#if RCT_DEV
|
||||||
CGSize imagePixelSize = RCTSizeInPixels(image.size, image.scale);
|
CGSize imagePixelSize = RCTSizeInPixels(image.size, image.scale);
|
||||||
CGSize screenPixelSize = RCTSizeInPixels(RCTScreenSize(), RCTScreenScale());
|
CGSize screenPixelSize = RCTSizeInPixels(RCTScreenSize(), RCTScreenScale());
|
||||||
@@ -719,7 +746,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
NSStringFromCGSize(screenPixelSize));
|
NSStringFromCGSize(screenPixelSize));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (image) {
|
if (image) {
|
||||||
completionHandler(nil, image);
|
completionHandler(nil, image);
|
||||||
} else {
|
} else {
|
||||||
@@ -728,7 +755,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
completionHandler(finalError, nil);
|
completionHandler(finalError, nil);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// We're no longer retaining the uncompressed data, so now we'll mark
|
// We're no longer retaining the uncompressed data, so now we'll mark
|
||||||
// the decoding as complete so that the loading task queue can resume.
|
// the decoding as complete so that the loading task queue can resume.
|
||||||
dispatch_async(self->_URLRequestQueue, ^{
|
dispatch_async(self->_URLRequestQueue, ^{
|
||||||
@@ -738,7 +765,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!_URLRequestQueue) {
|
if (!_URLRequestQueue) {
|
||||||
[self setUp];
|
[self setUp];
|
||||||
}
|
}
|
||||||
@@ -747,7 +774,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
// complete, so we'll mark it as having started, in order to block
|
// complete, so we'll mark it as having started, in order to block
|
||||||
// further image loads from happening until we're done with the data.
|
// further image loads from happening until we're done with the data.
|
||||||
self->_scheduledDecodes++;
|
self->_scheduledDecodes++;
|
||||||
|
|
||||||
if (!self->_pendingDecodes) {
|
if (!self->_pendingDecodes) {
|
||||||
self->_pendingDecodes = [NSMutableArray new];
|
self->_pendingDecodes = [NSMutableArray new];
|
||||||
}
|
}
|
||||||
@@ -759,7 +786,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[self->_pendingDecodes addObject:decodeBlock];
|
[self->_pendingDecodes addObject:decodeBlock];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return ^{
|
return ^{
|
||||||
atomic_store(&cancelled, YES);
|
atomic_store(&cancelled, YES);
|
||||||
};
|
};
|
||||||
@@ -773,7 +800,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
CGSize size;
|
CGSize size;
|
||||||
if ([imageOrData isKindOfClass:[NSData class]]) {
|
if ([imageOrData isKindOfClass:[NSData class]]) {
|
||||||
NSDictionary *meta = RCTGetImageMetadata(imageOrData);
|
NSDictionary *meta = RCTGetImageMetadata(imageOrData);
|
||||||
|
|
||||||
NSInteger imageOrientation = [meta[(id)kCGImagePropertyOrientation] integerValue];
|
NSInteger imageOrientation = [meta[(id)kCGImagePropertyOrientation] integerValue];
|
||||||
switch (imageOrientation) {
|
switch (imageOrientation) {
|
||||||
case kCGImagePropertyOrientationLeft:
|
case kCGImagePropertyOrientationLeft:
|
||||||
@@ -806,7 +833,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
}
|
}
|
||||||
callback(error, size);
|
callback(error, size);
|
||||||
};
|
};
|
||||||
|
|
||||||
return [self _loadImageOrDataWithURLRequest:imageURLRequest
|
return [self _loadImageOrDataWithURLRequest:imageURLRequest
|
||||||
size:CGSizeZero
|
size:CGSizeZero
|
||||||
scale:1
|
scale:1
|
||||||
@@ -844,7 +871,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
- (BOOL)canHandleRequest:(NSURLRequest *)request
|
- (BOOL)canHandleRequest:(NSURLRequest *)request
|
||||||
{
|
{
|
||||||
NSURL *requestURL = request.URL;
|
NSURL *requestURL = request.URL;
|
||||||
|
|
||||||
// If the data being loaded is a video, return NO
|
// If the data being loaded is a video, return NO
|
||||||
// Even better may be to implement this on the RCTImageURLLoader that would try to load it,
|
// Even better may be to implement this on the RCTImageURLLoader that would try to load it,
|
||||||
// but we'd have to run the logic both in RCTPhotoLibraryImageLoader and
|
// but we'd have to run the logic both in RCTPhotoLibraryImageLoader and
|
||||||
@@ -861,7 +888,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
RCTLogError(@"%@", error);
|
RCTLogError(@"%@", error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
NSString *query = requestURL.query;
|
NSString *query = requestURL.query;
|
||||||
if (
|
if (
|
||||||
query != nil &&
|
query != nil &&
|
||||||
@@ -871,7 +898,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
) {
|
) {
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (id<RCTImageURLLoader> loader in _loaders) {
|
for (id<RCTImageURLLoader> loader in _loaders) {
|
||||||
// Don't use RCTImageURLLoader protocol for modules that already conform to
|
// Don't use RCTImageURLLoader protocol for modules that already conform to
|
||||||
// RCTURLRequestHandler as it's inefficient to decode an image and then
|
// RCTURLRequestHandler as it's inefficient to decode an image and then
|
||||||
@@ -881,7 +908,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -893,7 +920,7 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
[delegate URLRequest:requestToken didCompleteWithError:error];
|
[delegate URLRequest:requestToken didCompleteWithError:error];
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *mimeType = nil;
|
NSString *mimeType = nil;
|
||||||
NSData *imageData = nil;
|
NSData *imageData = nil;
|
||||||
if (RCTImageHasAlpha(image.CGImage)) {
|
if (RCTImageHasAlpha(image.CGImage)) {
|
||||||
@@ -903,17 +930,17 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image,
|
|||||||
mimeType = @"image/jpeg";
|
mimeType = @"image/jpeg";
|
||||||
imageData = UIImageJPEGRepresentation(image, 1.0);
|
imageData = UIImageJPEGRepresentation(image, 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
|
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
|
||||||
MIMEType:mimeType
|
MIMEType:mimeType
|
||||||
expectedContentLength:imageData.length
|
expectedContentLength:imageData.length
|
||||||
textEncodingName:nil];
|
textEncodingName:nil];
|
||||||
|
|
||||||
[delegate URLRequest:requestToken didReceiveResponse:response];
|
[delegate URLRequest:requestToken didReceiveResponse:response];
|
||||||
[delegate URLRequest:requestToken didReceiveData:imageData];
|
[delegate URLRequest:requestToken didReceiveData:imageData];
|
||||||
[delegate URLRequest:requestToken didCompleteWithError:nil];
|
[delegate URLRequest:requestToken didCompleteWithError:nil];
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestToken;
|
return requestToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
#import <React/RCTEventEmitter.h>
|
#import <React/RCTEventEmitter.h>
|
||||||
#import <React/RCTNetworkTask.h>
|
#import <React/RCTNetworkTask.h>
|
||||||
|
#import <React/RCTURLRequestHandler.h>
|
||||||
|
|
||||||
@protocol RCTNetworkingRequestHandler <NSObject>
|
@protocol RCTNetworkingRequestHandler <NSObject>
|
||||||
|
|
||||||
@@ -26,6 +27,12 @@
|
|||||||
|
|
||||||
@interface RCTNetworking : RCTEventEmitter
|
@interface RCTNetworking : RCTEventEmitter
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows RCTNetworking instances to be initialized with handlers.
|
||||||
|
* The handlers will be requested via the bridge's moduleForName method when required.
|
||||||
|
*/
|
||||||
|
- (instancetype)initWithHandlersProvider:(NSArray<id<RCTURLRequestHandler>> * (^)(void))getHandlers;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Does a handler exist for the specified request?
|
* Does a handler exist for the specified request?
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
#import <React/RCTLog.h>
|
#import <React/RCTLog.h>
|
||||||
#import <React/RCTNetworkTask.h>
|
#import <React/RCTNetworkTask.h>
|
||||||
#import <React/RCTNetworking.h>
|
#import <React/RCTNetworking.h>
|
||||||
#import <React/RCTURLRequestHandler.h>
|
|
||||||
#import <React/RCTUtils.h>
|
#import <React/RCTUtils.h>
|
||||||
|
|
||||||
#import "RCTHTTPRequestHandler.h"
|
#import "RCTHTTPRequestHandler.h"
|
||||||
@@ -135,6 +134,7 @@ static NSString *RCTGenerateFormBoundary()
|
|||||||
NSMutableDictionary<NSNumber *, RCTNetworkTask *> *_tasksByRequestID;
|
NSMutableDictionary<NSNumber *, RCTNetworkTask *> *_tasksByRequestID;
|
||||||
std::mutex _handlersLock;
|
std::mutex _handlersLock;
|
||||||
NSArray<id<RCTURLRequestHandler>> *_handlers;
|
NSArray<id<RCTURLRequestHandler>> *_handlers;
|
||||||
|
NSArray<id<RCTURLRequestHandler>> * (^_handlersProvider)(void);
|
||||||
NSMutableArray<id<RCTNetworkingRequestHandler>> *_requestHandlers;
|
NSMutableArray<id<RCTNetworkingRequestHandler>> *_requestHandlers;
|
||||||
NSMutableArray<id<RCTNetworkingResponseHandler>> *_responseHandlers;
|
NSMutableArray<id<RCTNetworkingResponseHandler>> *_responseHandlers;
|
||||||
}
|
}
|
||||||
@@ -143,6 +143,14 @@ static NSString *RCTGenerateFormBoundary()
|
|||||||
|
|
||||||
RCT_EXPORT_MODULE()
|
RCT_EXPORT_MODULE()
|
||||||
|
|
||||||
|
- (instancetype)initWithHandlersProvider:(NSArray<id<RCTURLRequestHandler>> * (^)(void))getHandlers
|
||||||
|
{
|
||||||
|
if (self = [super init]) {
|
||||||
|
_handlersProvider = getHandlers;
|
||||||
|
}
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
|
||||||
- (void)invalidate
|
- (void)invalidate
|
||||||
{
|
{
|
||||||
for (NSNumber *requestID in _tasksByRequestID) {
|
for (NSNumber *requestID in _tasksByRequestID) {
|
||||||
@@ -174,8 +182,14 @@ RCT_EXPORT_MODULE()
|
|||||||
std::lock_guard<std::mutex> lock(_handlersLock);
|
std::lock_guard<std::mutex> lock(_handlersLock);
|
||||||
|
|
||||||
if (!_handlers) {
|
if (!_handlers) {
|
||||||
|
if (_handlersProvider) {
|
||||||
|
_handlers = _handlersProvider();
|
||||||
|
} else {
|
||||||
|
_handlers = [self.bridge modulesConformingToProtocol:@protocol(RCTURLRequestHandler)];
|
||||||
|
}
|
||||||
|
|
||||||
// Get handlers, sorted in reverse priority order (highest priority first)
|
// Get handlers, sorted in reverse priority order (highest priority first)
|
||||||
_handlers = [[self.bridge modulesConformingToProtocol:@protocol(RCTURLRequestHandler)] sortedArrayUsingComparator:^NSComparisonResult(id<RCTURLRequestHandler> a, id<RCTURLRequestHandler> b) {
|
_handlers = [_handlers sortedArrayUsingComparator:^NSComparisonResult(id<RCTURLRequestHandler> a, id<RCTURLRequestHandler> b) {
|
||||||
float priorityA = [a respondsToSelector:@selector(handlerPriority)] ? [a handlerPriority] : 0;
|
float priorityA = [a respondsToSelector:@selector(handlerPriority)] ? [a handlerPriority] : 0;
|
||||||
float priorityB = [b respondsToSelector:@selector(handlerPriority)] ? [b handlerPriority] : 0;
|
float priorityB = [b respondsToSelector:@selector(handlerPriority)] ? [b handlerPriority] : 0;
|
||||||
if (priorityA > priorityB) {
|
if (priorityA > priorityB) {
|
||||||
|
|||||||
Reference in New Issue
Block a user