在一个项目中,我想在网页视图中加载的http页面中下载mp3文件。下载的文件可以通过手机驱动器或保管箱等应用程序打开。
当用户单击Web视图中的链接时,它应该将其下载到iPhone。
在服务器端,mp3文件位于webroot之外。因此,下载链接类似于"download.php?id=554"
任何人都可以在这个问题上帮助我吗?我想知道有没有办法实现这一目标。谢谢
编辑
我添加了这个代表
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
var urlm = request.URL.absoluteURL?.absoluteString
if urlm?.rangeOfString("filename") != nil{
print(urlm)
//code to download (I NEED IT TOO)
return false
}
return true
}
但仍然不知道如何下载?
SwiftHTTP (https://github.com/daltoniam/swiftHTTP) 使我成为可能!
这么简单,我的朋友,
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
建议在单独的线程中执行代码。
对于大型下载:
-(IBAction) downloadButtonPressed:(id)sender;{
//download the file in a seperate thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Downloading Started");
NSString *urlToDownload = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(@"File Saved !");
});
}
});
}
我没有得到您的实际要求,但是您可以使用以下代码从URL下载文件。
NSString *stringURL = @"http://www.somewhere.com/Untitled.mp3";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
当您按下网页上的链接时,您可以从UIWebView委托方法获取mp3文件URL(从NSURLRequest对象读取)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return NO;
}
在 Swift 中创建 UIWebView,
override func viewDidLoad() {
super.viewDidLoad()
let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.somewhere.com")))
webV.delegate = self;
self.view.addSubview(webV)
}
当用户点击网页中的某个链接时,UIWebView会自动调用"shouldStartLoadWithRequest"方法,使用以下代码下载文件
func webView(webView: UIWebView!,
shouldStartLoadWithRequest request: NSURLRequest!,
navigationType navigationType: UIWebViewNavigationType) -> Bool {
println("Redirecting URL = (request.URL)")
//check if this is a mp3 file url and download
if(mp3 file)
{
let request:NSURLRequest = NSURLRequest(request.URL)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, mp3Data: NSData!, error: NSError!) -> Void in
let documentsPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let destinationPath:NSString = documentsPath.stringByAppendingString("/Untitled.mp3")
mp3Data.writeToFile(destinationPath, atomically: true)
return false
})
return true
}
我希望这有帮助
为了能够检测到来自此类链接的下载,您需要首先检查请求和导航类型 shouldStartLoadWithRequest
.
您需要检查一些内容,请求HTTPMethod
将是 POST,导航类型也将是 UIWebViewNavigationTypeFormSubmitted
、 UIWebViewNavigationTypeFormResubmitted
或 UIWebViewNavigationTypeLinkClicked
。您还需要解析请求 URL 的查询字符串,它将具有 response-content-disposition
、 attachment
或dl
密钥,如果它有一个,则它是一个文件下载。然后,您需要为请求创建一个NSURLConnection
并启动它,然后在 Web 视图委托中返回NO
。
以下是我检查应用程序中下载的方式。 (shouldStartLoadWithRequest
NSDictionary *dict = [url parseQueryString];
if (([[request.HTTPMethod uppercaseString] isEqualToString:@"POST"] &&
(navigationType == UIWebViewNavigationTypeFormSubmitted ||
navigationType == UIWebViewNavigationTypeFormResubmitted ||
navigationType == UIWebViewNavigationTypeLinkClicked)) || [[dict objectForKey:@"response-content-disposition"] isEqualToString:@"attachment"] || [[dict objectForKey:@"dl"] boolValue] == YES) {
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
return NO;
}
然后,您需要将NSURLConnection
委托方法添加到didReceiveResponse
。我检查标题字段中的一些键,然后如果它们通过,您可以开始下载,或者如果结果不是下载,则可以继续加载 Web 视图。(didReceiveResponse
)
if (urlResponse.allHeaderFields[@"Content-Disposition"] ||
([[urlResponse.allHeaderFields[@"Content-Type"] lowercaseString] containsString:@"text/html;"] == NO &&
[[urlResponse.allHeaderFields[@"Content-Type"] lowercaseString] containsString:@"charset=utf-8"] == NO )) {
// Start a download with NSURLSession with response.URL and connection.currentRequest
}
else {
[self.webView loadRequest:connection.currentRequest];
[connection cancel];
}