从UIWebView下载视频文件

时间:2015-06-26 05:58:35

标签: ios video download uiwebview

在我的应用程序中,我想从用户从UIWebView点击的任何可下载链接下载视频说.MP4格式,并保存在应用程序文档文件夹中。

以下是代码: -

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *url = [[webView request] URL];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
 [NSURLConnection connectionWithRequest: request delegate:self];

return YES;    
}

并收到回复

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)theResponse{
NSString* content_type = [[(NSHTTPURLResponse*)theResponse allHeaderFields] valueForKey:@"Content-Type"];
NSLog(@"Content type = %@",content_type);
if ([content_type isEqualToString:@"mp4"]) {
    NSData *urlData = [NSData dataWithContentsOfURL:[theResponse URL]];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath_ = [documentsDirectory stringByAppendingPathComponent:@""];
    NSString *newStr = [@"testVideo" stringByAppendingString:[NSString stringWithFormat:@".mp4"]];
    NSString *FilePath = [NSString stringWithFormat:@"%@/%@",dataPath_,newStr];
    [urlData writeToFile:FilePath atomically:YES];

}
}

第一次单击“下载”链接时,MIME类型始终为“text / html”,视频播放,单击后面,然后收到MIME类型“视频”,视频开始下载。 我想在第一次点击时下载视频。

我很感激一些帮助或示例代码。

0 个答案:

没有答案