gpt4 book ai didi

ios - 如何从 os x 中的 webview 下载文件并将其保存到特定位置

转载 作者:行者123 更新时间:2023-11-28 21:56:44 24 4
gpt4 key购买 nike

我到处都找遍了,但没有找到我要找的东西,所以这是我的问题:

我有一个正在玩的基本应用程序。我已经创建了一个 webview,并希望能够从加载到 webview 的网站下载一个文件,并将该文件保存到本地计算机上的 Downloads 文件夹中。该站点在 webview 中加载正常,现在我如何下载文件,比如从站点下载 .xml 文件并将其保存到本地计算机上的下载文件夹?

这是我目前所拥有的:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];//<-- example site
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[webView mainFrame] loadRequest:request];



}

我希望能够下载文件(可能使用委托(delegate)),然后将其保存到本地计算机上的某个位置。我对此很陌生,所以非常感谢任何帮助。

最佳答案

问题已经解决。我添加了以下代码以使其工作:

- (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
}

希望这对其他人有帮助。

关于ios - 如何从 os x 中的 webview 下载文件并将其保存到特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com