我到处寻找并且找不到我想要的东西,所以这是我的问题:
我有一个基本的应用程序,我正在玩。我已经创建了一个webview,并希望能够从加载到webview中的网站下载文件,并将文件保存到本地计算机上的“下载”文件夹中。该网站在webview中加载正常,现在如何下载文件,从网站上说一个.xml文件并将其保存到本地计算机上的Downloads文件夹中?
这是我到目前为止所做的:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];//<-- example site
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[webView mainFrame] loadRequest:request];
}
我希望能够下载文件(可能使用委托),然后将其保存到本地计算机上的某个位置。我对此很新,所以我很感激任何帮助。
答案 0 :(得分:2)
问题已经解决。我添加了以下代码以使其工作:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; // <-- example website
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.webView.policyDelegate = self;
[self.webView setDownloadDelegate:self];
[[self.webView mainFrame] loadRequest:request];
}
- (void)webView:(WebView *)webView decidePolicyForMIMEType:(NSString *)type
request:(NSURLRequest *)request
frame:(WebFrame *)frame
decisionListener:(id < WebPolicyDecisionListener >)listener
{
if([type isEqualToString:@"application/octet-stream"]) //this is the type I was looking for
{
//figure out how to save file here
[listener download];
NSURLDownload *downLoad = [[NSURLDownload alloc] initWithRequest:request delegate:self];
if(downLoad)
{
[self download:downLoad decideDestinationWithSuggestedFilename:@"filename.ext"];
NSLog(@"File Downloaded Succesfully");
//[webView close];
[self.window close];
}
else
{
NSLog(@"The download failed");
}
}
//just ignore all other types; the default behaviour will be used
}
-(void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
NSString *destinationFileName;
NSString *homeDirectory = NSHomeDirectory();
destinationFileName = [[homeDirectory stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename];
[download setDestination:destinationFileName allowOverwrite:NO]; //file is being saved to the Documents folder on the local machine
}
希望这会对其他人有所帮助。