【问题标题】:Implementing 'Download to Computer' functionality of browser实现浏览器的“下载到计算机”功能
【发布时间】:2012-12-08 22:38:31
【问题描述】:

我正在尝试使用NSURLConnection 在给定链接处下载mp3 文件。但是,我通常会收到超时错误。在浏览器中输入链接会显示默认播放器,但也不会加载音乐文件:

但是,如果我创建以下简单的 HTML 文件:

<html>
    <body>
        <a href="link_to_the_mp3" target="_blank">Download</a>
    </body>
</html>

然后将文件加载到Safari中,右键单击Download链接,然后选择Download to Computer(或任何英文名称),Safari下载文件。

关于如何在我自己的应用中实现这一点有什么想法吗?


我尝试过使用

NSData *data = [NSData dataWithContentsOfURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) { /.../ }];`

没有成功。

【问题讨论】:

  • @MichaelDautermann 我试过+dataWithContentsOfURL: (NSData) 和-sendAsynchronousRequest:queue:completionHandler: (NSURLConnection)。现在试试你的方法...
  • @MichaelDautermann 到目前为止看起来不错(做一些测试)。你能把你的评论变成答案吗?
  • 完成!我希望这个解决方案适合你...

标签: html objective-c macos download


【解决方案1】:

您似乎想用大锤击打苍蝇,使用“NSURLConnection”。

尝试做一些更高级别的事情,例如

NSData * mp3data = [[NSData alloc] initWithContentsOfURL:options:error: ];

(这里的额外好处是您可以通过传递给方法的“error:”参数返回有用的错误。

【讨论】:

    【解决方案2】:

    以下是您需要做的示例:

    NSURL* url = [NSURL URLWithString:yourMp3URLString];
    //URL of the mp3 file
    
    NSString* fileName = [NSString stringWithFormat:@"%@.mp3", mp3Name];
    //NSString with the name of the mp3
    
    NSString* destinationPath = [filePathString stringByAppendingPathComponent:fileName];
    //NSString with the filePathString (NSString with path destination, you could 
    //change it to something like this @"User/Desktop")
    //and add the NSString filename to the end of it
    //so, if we have like User/Desktop it will become User/Desktop/mp3Name.mp3
    
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSURLDownload* download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
    [download setDestination:destinationPath allowOverwrite:NO];
    //create the URLRequest and Download the mp3 to the destinationPath
    

    【讨论】:

    • 有趣,从来不知道这门课。立即查看。
    • 我不断收到kCFURLErrorCannotOpenFile 错误,所以现在,我将使用迈克尔的方法。
    猜你喜欢
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多