下载通过 PHP 为 WKwebview (iOS) 生成的服务器文件

Download a server file generated via PHP for WKwebview (iOS)

我在服务器上有一个 php 文件,当我通过任何网络浏览器访问它时,它会生成一个要下载的文件,即使是使用 safari。

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers 
header('Content-Type: application/text');

header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));

readfile($filename); 

我在我的应用程序中使用 WKwebview,我真正想做的是下载它并存储在我的应用程序沙盒文件夹中。 我尝试了多种下载文件的方法,但 WKwebview 总是下载 *.php 文件,而不是生成 de php.

的文件
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fileURL]];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
        
        NSString *aux= [response suggestedFilename];
        
        //return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        return [documentsDirectoryURL URLByAppendingPathComponent:@"db.bk"];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
        

        
    }];
    
    [downloadTask resume];

有下载的方法吗? (在 Objective-c)

谢谢!

更新: 目前,实现这个,我可以在 wkwebview 中以文本模式查看文件,但仍然无法下载它:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler 

iOS 14.5 您可以使用 WKDownloadDelegate 下载响应中的附件,并可以提供一个目的地 url 来保存:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    self.webView.navigationDelegate = self;
    
    NSURL* url = [NSURL URLWithString: @"https://your-domain.com/download.php"];
    NSURLRequest* request = [NSURLRequest requestWithURL: url];
    [self.webView loadRequest:request];
    
    [self.view addSubview:self.webView];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler {
    if (navigationResponse.canShowMIMEType) {
        decisionHandler(WKNavigationResponsePolicyAllow);
    } else {
        decisionHandler(WKNavigationResponsePolicyDownload);
    }
}

- (void)webView:(WKWebView *)webView navigationResponse:(WKNavigationResponse *)navigationResponse didBecomeDownload:(WKDownload *)download {
    download.delegate = self;
}

#pragma mark - WKDownloadDelegate

- (void)download:(WKDownload *)download decideDestinationUsingResponse:(NSURLResponse *)response suggestedFilename:(NSString *)suggestedFilename completionHandler:(void (^)(NSURL * _Nullable))completionHandler {
    // Save to Documents
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:suggestedFilename];
    NSURL* url = [NSURL fileURLWithPath:filePath];
    
    completionHandler(url);
}

- (void)downloadDidFinish:(WKDownload *)download {
    // Downloaded
}

对于以前的iOS版本,您应该手动下载返回的文件:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler {
    if (navigationResponse.canShowMIMEType) {
        decisionHandler(WKNavigationResponsePolicyAllow);
    }
    else {
        NSURL* downloadUrl = navigationResponse.response.URL;
        NSURLSessionDataTask* dataTask = [NSURLSession.sharedSession dataTaskWithURL:downloadUrl completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) {
            if (data != nil) {
                // Save to Documents
                NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *filePath = [documentPath stringByAppendingPathComponent:navigationResponse.response.suggestedFilename];
                [data writeToFile:filePath atomically:YES];
            }
        }];
        [dataTask resume];
        
        decisionHandler(WKNavigationResponsePolicyCancel);
    }
}

从上面的回答来看,如果下载需要cookie,或者下载的请求方法是POST,那么使用NSURLSessionDataTask是行不通的。