0

我正在使用 ASIHTTPRequest 在后台从 URL 下载视频文件。

我正在显示带有进度条和百分比的下载,我希望用户可以控制下载,例如暂停和恢复。

下面是代码:

 -(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
}
4

1 回答 1

1

您需要为每个请求保存请求的 URL 和目标路径并暂停请求使用代码:-

[请求取消];

要恢复请求,您需要创建另一个具有相同 URL 和目标路径的请求。例如 :-

    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];

在上面的代码中,我们从字典中获取歌曲的 url,该字典被设置为请求的 userInfo,现在我们获取这些详细信息以恢复请求。当我们恢复请求时,文件将从暂停点开始下载,从而解决了恢复文件下载的目的。

于 2012-12-07T06:42:29.190 回答