Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
ead60db
Add onProgress and onComplete callbacks for `preload` both on Android…
doomsower Aug 29, 2018
5c11dec
Merge branch 'master' into preload_callbacks
doomsower Jan 19, 2019
5f9b91c
Merge remote-tracking branch 'banana/preload_callbacks' into feature/…
Mickagd Mar 26, 2019
179af4c
fix flow
Mickagd Mar 28, 2019
29b01a9
fix: an empty sources array never called onComplete
Elindorath Apr 18, 2019
39d4cd5
Merge pull request #1 from DylanVann/master
Mickagd Jun 19, 2019
4c09121
Merge branch 'master' into feature/preload-callbacks
Mickagd Jun 19, 2019
40cb5b8
fix lint
Mickagd Jun 19, 2019
c86abda
update swebimage
Mickagd Jun 19, 2019
1d93c0d
Merge pull request #2 from DylanVann/master
joan-saum Oct 28, 2019
0f67ddb
Merge branch 'master' into feature/preload-callbacks
Nov 4, 2019
3812d45
Merge remote-tracking branch 'upstream/master' into feature/preload-c…
Aug 18, 2021
6dd7261
fix: revert FastImagePreloaderModule class to FastImageViewModule + a…
Aug 18, 2021
70fe646
fix lint
Aug 18, 2021
7dffb00
fix NativeEventEmitter mock in test
Aug 18, 2021
7dcb4ae
fix NativeEventEmitter mock in test
Aug 18, 2021
d7ea691
turn preloadermanager.js to typescript file
Aug 18, 2021
440ee83
fix lint + add listener to FastImageViewModule.java
Aug 19, 2021
2af79e5
bind context to listeners
Aug 19, 2021
f8d13ec
add SDWebImageDownloader.h import in FFFastImagePreloaderManager.m file
Aug 20, 2021
bbe6c9d
Merge pull request #4 from Sparted/feature/preload-callbacks-fetch-up…
Mickagd Aug 20, 2021
0ee6e1f
Merge branch 'main' into feature/preload-callbacks
Flictuum Jan 25, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,21 +188,25 @@ In this case the image will still be styled and laid out the same way as `FastIm

## Static Methods

### `FastImage.preload: (source[]) => void`
### `FastImage.preload: (source[], onProgress?, onComplete?) => void`

Preload images to display later. e.g.

```js
FastImage.preload([
FastImage.preload(
[
{
uri: 'https://facebook.github.io/react/img/logo_og.png',
headers: { Authorization: 'someAuthToken' },
uri: 'https://facebook.github.io/react/img/logo_og.png',
headers: { Authorization: 'someAuthToken' },
},
{
uri: 'https://facebook.github.io/react/img/logo_og.png',
headers: { Authorization: 'someAuthToken' },
uri: 'https://facebook.github.io/react/img/logo_og.png',
headers: { Authorization: 'someAuthToken' },
},
])
],
(finished, total) => console.log(`Preloaded ${finished}/${total} images`),
(finished, skipped) => console.log(`Completed. Failed to load ${skipped}/${finished} images`),
)
```

## Troubleshooting
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.dylanvann.fastimage;

import android.support.annotation.Nullable;
import android.util.Log;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.io.File;

class FastImagePreloaderListener implements RequestListener<File> {
private static final String LOG = "[FFFastImage]";
private static final String EVENT_PROGRESS = "fffastimage-progress";
private static final String EVENT_COMPLETE = "fffastimage-complete";

private final ReactApplicationContext reactContext;
private final int id;
private final int total;
private int succeeded = 0;
private int failed = 0;

public FastImagePreloaderListener(ReactApplicationContext reactContext, int id, int totalImages) {
this.id = id;
this.reactContext = reactContext;
this.total = totalImages;
}

@Override
public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<File> target, boolean b) {
// o is whatever was passed to .load() = GlideURL, String, etc.
Log.d(LOG, "Preload failed: " + o.toString());
this.failed++;
this.dispatchProgress();
return false;
}

@Override
public boolean onResourceReady(File file, Object o, Target<File> target, DataSource dataSource, boolean b) {
// o is whatever was passed to .load() = GlideURL, String, etc.
Log.d(LOG, "Preload succeeded: " + o.toString());
this.succeeded++;
this.dispatchProgress();
return false;
}

private void maybeDispatchComplete() {
if (this.failed + this.succeeded >= this.total) {
WritableMap params = Arguments.createMap();
params.putInt("id", this.id);
params.putInt("finished", this.succeeded + this.failed);
params.putInt("skipped", this.failed);
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(EVENT_COMPLETE, params);
}
}

private void dispatchProgress() {
WritableMap params = Arguments.createMap();
params.putInt("id", this.id);
params.putInt("finished", this.succeeded + this.failed);
params.putInt("total", this.total);
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(EVENT_PROGRESS, params);
this.maybeDispatchComplete();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.views.imagehelper.ImageSource;

class FastImageViewModule extends ReactContextBaseJavaModule {
class FastImagePreloaderModule extends ReactContextBaseJavaModule {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why rename class just like that. I have #425 which edit FastImageViewModule.java


private static final String REACT_CLASS = "FastImageView";
private static final String REACT_CLASS = "FastImagePreloaderManager";
private int preloaders = 0;

FastImageViewModule(ReactApplicationContext reactContext) {
FastImagePreloaderModule(ReactApplicationContext reactContext) {
super(reactContext);
}

Expand All @@ -25,18 +27,25 @@ public String getName() {
}

@ReactMethod
public void preload(final ReadableArray sources) {
public void createPreloader(Promise promise) {
promise.resolve(preloaders++);
}

@ReactMethod
public void preload(final int preloaderId, final ReadableArray sources) {
final Activity activity = getCurrentActivity();
if (activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
FastImagePreloaderListener preloader = new FastImagePreloaderListener(getReactApplicationContext(), preloaderId, sources.size());
for (int i = 0; i < sources.size(); i++) {
final ReadableMap source = sources.getMap(i);
final FastImageSource imageSource = FastImageViewConverter.getImageSource(activity, source);

Glide
.with(activity.getApplicationContext())
.downloadOnly()
// This will make this work for remote and local images. e.g.
// - file:///
// - content://
Expand All @@ -47,6 +56,7 @@ public void run() {
imageSource.isBase64Resource() ? imageSource.getSource() :
imageSource.isResource() ? imageSource.getUri() : imageSource.getGlideUrl()
)
.listener(preloader)
.apply(FastImageViewConverter.getOptions(source))
.preload();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public class FastImageViewPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.<NativeModule>singletonList(new FastImageViewModule(reactContext));
return Collections.<NativeModule>singletonList(new FastImagePreloaderModule(reactContext));
}

@Override
Expand Down
12 changes: 12 additions & 0 deletions ios/FastImage.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
objects = {

/* Begin PBXBuildFile section */
75470991212F3C590040708C /* FFFastImagePreloaderManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 75470990212F3C590040708C /* FFFastImagePreloaderManager.m */; };
75470994212F409B0040708C /* FFFastImagePreloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 75470993212F409B0040708C /* FFFastImagePreloader.m */; };
FCC6D1391EB3912D0065F944 /* libSDWebImage iOS static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = FCC6D0D01EB38D2F0065F944 /* libSDWebImage iOS static.a */; };
FCFB253F1EA5562700F59778 /* FFFastImageSource.m in Sources */ = {isa = PBXBuildFile; fileRef = FCFB25381EA5562700F59778 /* FFFastImageSource.m */; };
FCFB25401EA5562700F59778 /* FFFastImageView.m in Sources */ = {isa = PBXBuildFile; fileRef = FCFB253A1EA5562700F59778 /* FFFastImageView.m */; };
Expand Down Expand Up @@ -79,6 +81,10 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
7547098A212F3BE70040708C /* FFFastImagePreloaderManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FFFastImagePreloaderManager.h; sourceTree = "<group>"; };
75470990212F3C590040708C /* FFFastImagePreloaderManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FFFastImagePreloaderManager.m; sourceTree = "<group>"; };
75470992212F3F9A0040708C /* FFFastImagePreloader.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FFFastImagePreloader.h; sourceTree = "<group>"; };
75470993212F409B0040708C /* FFFastImagePreloader.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FFFastImagePreloader.m; sourceTree = "<group>"; };
A287971D1DE0C0A60081BDFA /* libFastImage.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libFastImage.a; sourceTree = BUILT_PRODUCTS_DIR; };
FCC6D0C61EB38D2F0065F944 /* SDWebImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SDWebImage.xcodeproj; path = Vendor/SDWebImage/SDWebImage.xcodeproj; sourceTree = "<group>"; };
FCFB25371EA5562700F59778 /* FFFastImageSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FFFastImageSource.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -152,6 +158,10 @@
FCFB253C1EA5562700F59778 /* FFFastImageViewManager.m */,
FCFB253D1EA5562700F59778 /* RCTConvert+FFFastImage.h */,
FCFB253E1EA5562700F59778 /* RCTConvert+FFFastImage.m */,
7547098A212F3BE70040708C /* FFFastImagePreloaderManager.h */,
75470990212F3C590040708C /* FFFastImagePreloaderManager.m */,
75470992212F3F9A0040708C /* FFFastImagePreloader.h */,
75470993212F409B0040708C /* FFFastImagePreloader.m */,
);
path = FastImage;
sourceTree = "<group>";
Expand Down Expand Up @@ -265,10 +275,12 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
75470994212F409B0040708C /* FFFastImagePreloader.m in Sources */,
FCFB25411EA5562700F59778 /* FFFastImageViewManager.m in Sources */,
FCFB25421EA5562700F59778 /* RCTConvert+FFFastImage.m in Sources */,
FCFB25401EA5562700F59778 /* FFFastImageView.m in Sources */,
FCFB253F1EA5562700F59778 /* FFFastImageSource.m in Sources */,
75470991212F3C590040708C /* FFFastImagePreloaderManager.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
9 changes: 9 additions & 0 deletions ios/FastImage/FFFastImagePreloader.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#import "FFFastImageSource.h"
#import <Foundation/Foundation.h>
#import <SDWebImage/SDWebImagePrefetcher.h>

@interface FFFastImagePreloader : SDWebImagePrefetcher

@property (nonatomic, readonly) NSNumber* id;

@end
16 changes: 16 additions & 0 deletions ios/FastImage/FFFastImagePreloader.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#import "FFFastImagePreloader.h"
#import "FFFastImageSource.h"

static int instanceCounter = 0;

@implementation FFFastImagePreloader

-(instancetype) init {
if (self = [super init]) {
instanceCounter ++;
_id = [NSNumber numberWithInt:instanceCounter];
}
return self;
}

@end
7 changes: 7 additions & 0 deletions ios/FastImage/FFFastImagePreloaderManager.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <SDWebImage/SDWebImagePrefetcher.h>

@interface FFFastImagePreloaderManager : RCTEventEmitter <RCTBridgeModule, SDWebImagePrefetcherDelegate>

@end
78 changes: 78 additions & 0 deletions ios/FastImage/FFFastImagePreloaderManager.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#import "FFFastImagePreloaderManager.h"
#import "FFFastImagePreloader.h"
#import "FFFastImageSource.h"

@implementation FFFastImagePreloaderManager
{
bool _hasListeners;
NSMutableDictionary* _preloaders;
}

RCT_EXPORT_MODULE(FastImagePreloaderManager);

- (dispatch_queue_t)methodQueue
{
return dispatch_queue_create("com.dylanvann.fastimage.FastImagePreloaderManager", DISPATCH_QUEUE_SERIAL);
}

+ (BOOL)requiresMainQueueSetup
{
return YES;
}

-(instancetype) init {
if (self = [super init]) {
_preloaders = [[NSMutableDictionary alloc] init];
}
return self;
}

- (NSArray<NSString *> *)supportedEvents
{
return @[@"fffastimage-progress", @"fffastimage-complete"];
}

- (void) imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher
didFinishWithTotalCount:(NSUInteger)totalCount
skippedCount:(NSUInteger)skippedCount
{
NSNumber* id = ((FFFastImagePreloader*) imagePrefetcher).id;
[_preloaders removeObjectForKey:id];
[self sendEventWithName:@"fffastimage-complete"
body:@{ @"id": id, @"finished": [NSNumber numberWithLong:totalCount], @"skipped": [NSNumber numberWithLong:skippedCount]}
];
}

- (void) imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher
didPrefetchURL:(nullable NSURL *)imageURL
finishedCount:(NSUInteger)finishedCount
totalCount:(NSUInteger)totalCount
{
NSNumber* id = ((FFFastImagePreloader*) imagePrefetcher).id;
[self sendEventWithName:@"fffastimage-progress"
body:@{ @"id": id, @"finished": [NSNumber numberWithLong:finishedCount], @"total": [NSNumber numberWithLong:totalCount] }
];
}

RCT_EXPORT_METHOD(createPreloader:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
FFFastImagePreloader* preloader = [[FFFastImagePreloader alloc] init];
preloader.delegate = self;
_preloaders[preloader.id] = preloader;
resolve(preloader.id);
}

RCT_EXPORT_METHOD(preload:(nonnull NSNumber*)preloaderId sources:(nonnull NSArray<FFFastImageSource *> *)sources) {
NSMutableArray *urls = [NSMutableArray arrayWithCapacity:sources.count];

[sources enumerateObjectsUsingBlock:^(FFFastImageSource * _Nonnull source, NSUInteger idx, BOOL * _Nonnull stop) {
[source.headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString* header, BOOL *stop) {
[[SDWebImageDownloader sharedDownloader] setValue:header forHTTPHeaderField:key];
}];
[urls setObject:source.url atIndexedSubscript:idx];
}];

FFFastImagePreloader* preloader = _preloaders[preloaderId];
[preloader prefetchURLs:urls];
}

@end
16 changes: 0 additions & 16 deletions ios/FastImage/FFFastImageViewManager.m
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#import "FFFastImageViewManager.h"
#import "FFFastImageView.h"

#import <SDWebImage/SDWebImagePrefetcher.h>

@implementation FFFastImageViewManager

RCT_EXPORT_MODULE(FastImageView)
Expand All @@ -19,19 +17,5 @@ - (FFFastImageView*)view {
RCT_EXPORT_VIEW_PROPERTY(onFastImageLoad, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onFastImageLoadEnd, RCTDirectEventBlock)

RCT_EXPORT_METHOD(preload:(nonnull NSArray<FFFastImageSource *> *)sources)
{
NSMutableArray *urls = [NSMutableArray arrayWithCapacity:sources.count];

[sources enumerateObjectsUsingBlock:^(FFFastImageSource * _Nonnull source, NSUInteger idx, BOOL * _Nonnull stop) {
[source.headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString* header, BOOL *stop) {
[[SDWebImageDownloader sharedDownloader] setValue:header forHTTPHeaderField:key];
}];
[urls setObject:source.url atIndexedSubscript:idx];
}];

[[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:urls];
}

@end

Loading