Tengo un archivo php en el servidor que genera un archivo para descargar cuando accedo a él a través de cualquier navegador web, incluso con 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);Estoy usando WKwebview en mi aplicación, y lo que realmente quiero hacer es descargarlo y almacenarlo en la carpeta sandbox de mi aplicación. He intentado varias formas de descargar el archivo, pero WKwebview siempre descarga el archivo *.php, no el archivo que genera 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];Hay alguna forma de descargarlo? (en Objetivo-c)
¡Gracias!
ACTUALIZACIÓN: actualmente, implementando esto, puedo ver el archivo en modo texto en wkwebview, pero aún no puedo descargarlo:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandlerDesde iOS 14.5 , puede usar WKDownloadDelegate para descargar archivos adjuntos en las respuestas y puede proporcionar una URL de destino para guardar:
- (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 }Para versiones anteriores de iOS , debe descargar un archivo devuelto manualmente:
- (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); } }De la respuesta anterior, si la descarga requiere una cookie, o si el método de solicitud para la descarga es POST, el uso de NSURLSessionDataTask no funcionará.