0

I have trying to download the multiple .mp3 files from a server at time. One complete audio file is divided into 286 parts. I fetch all the urls of the file and now I want to download 286 files. I search a lot but many library stop downloading when I go back to previous controller and if user minimize the app the downloaded stop. Is there any library which can manage multiple downloads and download didn't stop when user go back to previous controller of minimize the app. I am using Download Manager library but I can't get my desired. Please give me the solution. I am stuck with that from 3 days . Please tell me the solution . Thanks

Muhammad Salman
  • 543
  • 4
  • 22

1 Answers1

0

In my project I'm using AFNetwirking. You can create a singleton object, and here is my method (for example) for downloading files :

- (AFHTTPRequestOperation *)performDownloadWithURLString:(nonnull NSString *)urlString
                                     destinationPath:(NSString *)destinationPath
                                            progress:(void (^)(long long bytesRead, long long totalBytesToRead))progress
                                         apiCallback:(void(^)(BOOL isSuccessful, id object))apiCallback
{

    NSURL *url = [NSURL URLWithString:urlString];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSString *fullPath = [[FCFileManager pathForTemporaryDirectory] stringByAppendingPathComponent:[url lastPathComponent]];

    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
     {
         if(progress) {
             progress(totalBytesRead, totalBytesExpectedToRead);
         }
     }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            if(destinationPath && [FCFileManager isFileItemAtPath:destinationPath]) {
                NSError *removeError;
                [FCFileManager removeItemAtPath:destinationPath error:&removeError];
            }
            if(destinationPath) {
                [FCFileManager moveItemAtPath:fullPath toPath:destinationPath];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                if(apiCallback) {
                    apiCallback(YES, destinationPath ?: fullPath);
                }
            });
        });

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSError *removeError;
        [FCFileManager removeItemAtPath:fullPath error:&removeError];

        if(apiCallback) {
            apiCallback(NO, [AZError errorWithNSError:error]);
        }

    }];
    [operation start];
}

Hope it helps you.