实现浏览器的“下载到计算机”功能

时间:2012-12-08 13:20:37

标签: html objective-c macos download

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

Downloading mp3's is not illegal in all countries

但是,如果我创建以下简单的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) { /.../ }];`

没有成功。

2 个答案:

答案 0 :(得分:2)

好像你正试图用大锤击中苍蝇,使用“NSURLConnection”。

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

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

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

答案 1 :(得分:1)

以下是您需要做的示例:

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