iOS WKWebView下载PHP生成的服务器文件 Objective-C实现方案咨询
问题根因
你之前单独发起的下载请求没有和WKWebView的会话信息同步,缺少必要的Cookie、User-Agent等请求头参数,导致服务器没有正常执行PHP逻辑返回生成的附件,才会返回异常内容。可以直接在你已经实现的webView:decidePolicyForNavigationResponse:decisionHandler:代理方法中处理下载逻辑,保证请求上下文和WKWebView完全一致。
完整实现代码
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response; // 校验是否为附件下载响应 NSString *contentDisposition = response.allHeaderFields[@"Content-Disposition"]; if (contentDisposition && [contentDisposition containsString:@"attachment"]) { // 取消WKWebView默认加载行为,自定义下载逻辑 decisionHandler(WKNavigationResponsePolicyCancel); // 同步WKWebView内的全部Cookie,保证请求身份和前端一致 [webView.configuration.websiteDataStore.httpCookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) { NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:response.URL]; // 注入WKWebView携带的Cookie NSDictionary *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; [downloadRequest setAllHTTPHeaderFields:cookieHeader]; // 同步WKWebView的User-Agent,避免服务器校验拦截 [downloadRequest setValue:webView.customUserAgent ?: [WKWebView class].description forHTTPHeaderField:@"User-Agent"]; // 发起下载请求 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:downloadRequest progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *docDir = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil]; // 优先取响应头返回的文件名, fallback为自定义文件名 NSString *fileName = [response suggestedFilename] ?: @"db.bk"; return [docDir URLByAppendingPathComponent:fileName]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { if (error) { NSLog(@"下载失败: %@", error.localizedDescription); return; } NSLog(@"下载成功,沙盒路径: %@", filePath); // 此处添加下载完成后续业务逻辑 }]; [downloadTask resume]; }]; return; } // 非下载类响应走WKWebView默认加载逻辑 decisionHandler(WKNavigationResponsePolicyAllow); }
额外校验项
如果按上述方案仍有异常,可先确认服务器侧配置:
- 浏览器直接访问PHP地址时是否能正常下载目标文件,排除服务器未正确解析PHP、直接返回源码的问题
- 确认服务端是否有额外的请求头校验规则,如有需要在
downloadRequest中补充对应头字段
内容的提问来源于stack exchange,提问作者Kotik_o
相关产品推荐
相关产品推荐

