Home > Back-end >  Download a server file generated via PHP for WKwebview (iOS)
Download a server file generated via PHP for WKwebview (iOS)

Time:11-17

I have a php file on the server that generates a file to download when I access to it via any web browser, even with 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); 

I'm using the WKwebview in my app, and what I really want to do is to download it and store is in my app sandbox folder. I have tried multiple ways to download the file but the WKwebview always download the *.php file, not the file that generates 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];

There is a way to download it? (in Objective-c)

Thanks!

UPDATE: currently, Implementing this, I can see the file in text mode in the wkwebview, but still not be able to download it:

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

CodePudding user response:

From iOS 14.5 you can use WKDownloadDelegate to download attached files in responses and can provide a destination url to save:

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

For previous iOS versions you should download a returned file manually:

- (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);
    }
}
  • Related