Ios 使用web视图下载文件

Ios 使用web视图下载文件,ios,xcode,swift,download,Ios,Xcode,Swift,Download,在一个项目中,我想在web视图中加载的http页面中下载mp3文件。下载的文件可以通过诸如phone drive或dropbox之类的应用程序打开 当用户单击web视图中的链接时,应将其下载到iphone 在服务器端,mp3文件位于webroot之外。因此,下载链接类似于“download.php?id=554” 有人能在这个问题上帮助我吗? 我想知道有没有办法做到这一点。谢谢 编辑 我添加了这个代表 func webView(webView: UIWebView!, shouldStartLo

在一个项目中,我想在web视图中加载的http页面中下载mp3文件。下载的文件可以通过诸如phone drive或dropbox之类的应用程序打开

当用户单击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
    }

但是仍然不知道如何下载?

我没有得到您的实际要求,但是您可以使用下面的代码从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
将被发布,并且导航类型将是
UIWebViewNavigationTypeFormSubmitted
UIWebViewNavigationTypeFormResubmitted
,或者
UIWebViewNavigationTypeLinkClicked
。您还需要解析请求URL的查询字符串,它将具有
响应内容配置
附件
、或
dl
键,如果有,则为文件下载。然后需要为请求创建一个
NSURLConnection
,并启动它,然后在web视图委托中返回
NO

下面是我如何在我的应用程序中检查下载。(进入
shouldStartLoadWithRequest

然后需要添加
NSURLConnection
委托方法
didReceiveResponse
。我在标题字段中检查一些键,然后如果它们通过,您可以开始下载,或者如果结果不是下载,则让web视图继续加载。(进入接收方回复中)


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

    });

}

我的“dataWithContentsOfURL(uuxOfURL:options:error:)”不可用:使用对象构造“NSData(contentsOfURL:options:error:)”“let mp3Data….”处的错误“NSData(contentsOfURL:options:error:)”看起来不推荐使用。顺便说一句,用户在webview上单击的链接不是mp3文件,它类似于“download.php?getfileid=7767”“那就不是我的地盘了。它也得到了广泛的支持。它来自于开发者为什么你接受你自己的悬赏问题的答案?有很多有用的答案。
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 !");
            });
        }

    });

}