Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handy solution to *joltup/rn-fetch-blob* iOS parallel download broken problem
var DownloadManagerIOS = NativeModules.DownloadManager;
DownloadManagerIOS.downloadList(imageLinkListForIOS, (el) => {
// el is list of path
});
//
// DownloadManager.h
//
// Created by Mohammad Julfikar on 22/05/2019.
// Copyright © 2019 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
NS_ASSUME_NONNULL_BEGIN
@interface DownloadManager : NSObject<RCTBridgeModule>
@end
NS_ASSUME_NONNULL_END
//
// DownloadManager.m
// ESv2
//
// Created by Mohammad Julfikar on 22/05/2019.
// Copyright © 2019 Facebook. All rights reserved.
//
#import "DownloadManager.h"
@implementation DownloadManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(downloadList:(NSArray*)data savedPath:(RCTResponseSenderBlock)callback){
NSMutableArray *finalList = [[NSMutableArray alloc]init];
size_t size = data.count;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
documentsPath = [NSString stringWithFormat:@"%@/Downloads/Images",documentsPath];
NSError *error = nil;
if(![fileManager createDirectoryAtPath:documentsPath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(@"Failed to create directory \"%@\". Error: %@", documentsPath, error);
}
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(@[finalList]);
}];
}];
for (size_t i = 0; i < size; i++){
NSString* trimmedUrlString = [data[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *url = [NSURL URLWithString:trimmedUrlString];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *filename = [documentsPath stringByAppendingPathComponent:[url lastPathComponent]];
if (![[NSFileManager defaultManager] fileExistsAtPath:filename] && data != nil)
{
if([data writeToFile:filename atomically:YES])
{
//NSLog(@"Saved");
[finalList addObject:filename];
}
else
{
NSLog(@"Failed to download");
}
}
}];
[completionOperation addDependency:operation];
}
[queue addOperations:completionOperation.dependencies waitUntilFinished:NO];
[queue addOperation:completionOperation];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.