简体   繁体   中英

ASIHTTPRequest multiple downloads control like pause, resume

I am using ASIHTTPRequest to download video file from URL in background.

I am displaying the downloads with progress-bar & percentage and I want user can control the downloads like pause & resume.

Below is the code:

 -(void)Initiate_Download:(NSString*)urlStr contentID:(NSString*)cid progressBar:(UIProgressView*)progressBar
 {
     NSLog(@"Initiate_Download for cid:%@",cid);

    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];

    NSString *fileName = [NSString stringWithFormat:@"%@.mp4",cid];
    NSString *destinationPath = [[self VideoDownloadFolderPath]stringByAppendingPathComponent:fileName];

    [request setDownloadDestinationPath:destinationPath];   
    [request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@-part",destinationPath]];
    [request setDelegate:self];

    NSDictionary *rqstDict = [NSDictionary dictionaryWithObjectsAndKeys:cid,@"cid",urlStr,@"url", nil];
    [request setUserInfo:rqstDict];
    [request setAllowResumeForFileDownloads:YES];
    [request startAsynchronous];
}

 //Delegate
- (void)requestStarted:(ASIHTTPRequest *)request1
{
    //some code
}
- (void)request:(ASIHTTPRequest *)request1 didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
   //some code
}
- (void)requestFinished:(ASIHTTPRequest *)request1
{
   //some code
}
- (void)requestFailed:(ASIHTTPRequest *)request1
{
  //some code
}

You need to save the URL and destination path of the request for each request and to pause the request use code :-

[request Cancel];

and to resume the request you need to create another request with same URL and destination path. For example :-

    ASIHTTPRequest *requestToResume = [ASIHTTPRequest requestWithURL:url];
    [requestToResume setTemporaryFileDownloadPath:tempfilePath];
    [requestToResume setDownloadDestinationPath:filePath]; 
    [requestToResume setDelegate:self];
    [requestToResume setDownloadProgressDelegate:self];
    [requestToResume setUserInfo:dictInfo];

    // This file has part of the download in it already
    [requestToResume setAllowResumeForFileDownloads:YES];
    [requestToResume setDidFinishSelector:@selector(requestDone:)];
    [requestToResume setDidFailSelector:@selector(requestWentWrong:)];
    [requestToResume startAsynchronous];

In the above code we get the url of the song from the dictionary which was set as userInfo of the request and now we get these details for resuming the request. When we resume the request the file will be downloaded from the point it was paused, hence it will solve the purpose of resuming the file download.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM