使用Web视图下载文件

时间:2015-03-09 17:11:03

标签: ios xcode swift download

在一个项目中,我想在Web视图中加载的http页面中下载mp3文件。下载的文件可以通过手机驱动器或Dropbox等应用程序打开。

当用户点击网页视图中的链接时,应将其下载到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
    }

但仍然不知道如何下载?

4 个答案:

答案 0 :(得分:1)

SwiftHTTP(https://github.com/daltoniam/swiftHTTP)使我成为可能!

答案 1 :(得分:1)

这就是我的朋友,

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 !");
            });
        }

    });

}

答案 2 :(得分:0)

我没有得到您的实际要求,但您可以使用以下代码从网址下载文件。

NSString *stringURL = @"http://www.somewhere.com/Untitled.mp3";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];

当您按下网页上的链接时,您可以从UIWebView委托方法获取mp3文件网址(从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
}

我希望这会有所帮助

答案 3 :(得分:0)

为了能够从类似的链接中检测到下载,您需要先在shouldStartLoadWithRequest中检查请求和导航类型。

您需要检查一些内容,请求HTTPMethod将是POST,导航类型也可以是UIWebViewNavigationTypeFormSubmittedUIWebViewNavigationTypeFormResubmittedUIWebViewNavigationTypeLinkClicked。您还需要解析请求URL的查询字符串,它将包含response-content-dispositionattachmentdl密钥,如果有,则为文件下载。然后,您需要为请求创建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];
            }