ASIHTTPRequest多次下载控制,如暂停,恢复

时间:2012-12-07 05:58:02

标签: iphone objective-c ios asihttprequest download-manager

我正在使用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
}

1 个答案:

答案 0 :(得分: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,现在我们获取这些恢复请求的详细信息。当我们恢复请求时,文件将从暂停的位置下载,因此它将解决恢复文件下载的目的。