拦截Webview的下载文件请求无法下载实际文件

时间:2018-08-11 09:46:02

标签: ios swift webview intercept nsurlsessiondownloadtask

我正在拦截下载pdf文件的webview请求。工作正常,但突然停止工作,即使我在请求中设置烹饪,它也会返回要求登录的login.html文件。

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){

        if let httpResponse = navigationResponse.response as? HTTPURLResponse, let url = httpResponse.url {
            let allHeaders = httpResponse.allHeaderFields.reduce([String : String](), { (result, next) -> [String : String] in
                guard let stringKey = next.key as? String, let stringValue = next.value as? String else { return result }
                var buffer = result
                buffer[stringKey] = stringValue
                return buffer
            })
            let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaders, for: url)
            for cookie in cookies {
                HTTPCookieStorage.shared.setCookie(cookie)
            }
            //trying
            if let newURL = navigationResponse.response.url?.absoluteString.contains("export"), newURL == true{


                var urlRequest = URLRequest(url: navigationResponse.response.url!)
                urlRequest.httpMethod = "POST"
                urlRequest.setValue(httpResponse.suggestedFilename, forHTTPHeaderField: "attachment")
                urlRequest.setValue("application/pdf", forHTTPHeaderField: "Content-Type")
                urlRequest.setValue("iPhone", forHTTPHeaderField: "User-Agent")
                print("Cookies: \(String(describing: HTTPCookieStorage.shared.cookies))")
                if let cookies = HTTPCookieStorage.shared.cookies {
                    print(cookies)
                    for cookie in cookies {
                        urlRequest.setValue(cookie.value, forHTTPHeaderField: cookie.name)
                    }
                }
                let task = DownloadManager.shared.activate().downloadTask(with: urlRequest)
                task.resume()
                decisionHandler(.cancel)
            }else {
                decisionHandler(.allow)
            }
        }
} 

请求代码:

func activate() -> URLSession {

        let config = URLSessionConfiguration.default
        // Warning: If an URLSession still exists from a previous download, it doesn't create a new URLSession object but returns the existing one with the old delegate object attached!
        let session = URLSession(configuration: config, delegate: self, delegateQueue:nil)
        return session
    }


 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        debugPrint("download description \(downloadTask.debugDescription)")

        var status = false
        do {
            let loadedData = try Data(contentsOf: location)
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let documentPath = documentsPath.appendingFormat("/%@",(downloadTask.response?.suggestedFilename)!)
            debugPrint("suggestedFilename \(downloadTask.response?.mimeType)")
            debugPrint("loaded path \(documentPath)")
            status = true

            do {
                try loadedData.write(to: URL(fileURLWithPath: documentPath), options: .atomic)
            } catch {
                debugPrint ("loading error 1")
            }
        } catch {
            debugPrint ("loading error 2")
        }
    }
}

响应

<WKNavigationResponse: 0x7f8cf2e0aaa0; response = <NSHTTPURLResponse: 0x600000224200> { URL: http://my.website.com/cases/export } { Status Code: 200, Headers {
    "Cache-Control" =     (
        "public, must-revalidate, max-age=0"
    );
    Connection =     (
        "keep-alive"
    );
    "Content-Description" =     (
        "File Transfer"
    );
    "Content-Disposition" =     (
        "attachment; filename=\"sample.pdf\""
    );
    "Content-Transfer-Encoding" =     (
        binary
    );
    "Content-Type" =     (
        "application/pdf"
    );
    Date =     (
        "Sat, 11 Aug 2018 09:20:36 GMT"
    );
    Expires =     (
        "Sat, 26 Jul 1997 05:00:00 GMT"
    );
    "Last-Modified" =     (
        "Sat, 11 Aug 2018 09:20:36 GMT"
    );
    Pragma =     (
        public
    );
    Server =     (
        "nginx/1.14.0"
    );
    "Set-Cookie" =     (
        "debuguser=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0"
    );
    "Transfer-Encoding" =     (
        Identity
    );
} }>

navigationAction.request

 ▿ 13 elements   ▿ 0 : 2 elements
    - key : "Pragma"
    - value : "public"   ▿ 1 : 2 elements
    - key : "Content-Transfer-Encoding"
    - value : "binary"   ▿ 2 : 2 elements
    - key : "Last-Modified"
    - value : "Sun, 19 Aug 2018 18:36:49 GMT"   ▿ 3 : 2 elements
    - key : "Content-Type"
    - value : "application/pdf"   ▿ 4 : 2 elements
    - key : "Connection"
    - value : "keep-alive"   ▿ 5 : 2 elements
    - key : "Set-Cookie"
    - value : "debuguser=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0"   ▿ 6 : 2 elements
    - key : "Content-Disposition"
    - value : "attachment; filename=\"StageTestCompany-cases-20-08-2018-1534703806.pdf\""   ▿ 7 : 2 elements
    - key : "Expires"
    - value : "Sat, 26 Jul 1997 05:00:00 GMT"   ▿ 8 : 2 elements
    - key : "Content-Description"
    - value : "File Transfer"   ▿ 9 : 2 elements
    - key : "Transfer-Encoding"
    - value : "Identity"   ▿ 10 : 2 elements
    - key : "Server"
    - value : "nginx/1.14.0"   ▿ 11 : 2 elements
    - key : "Cache-Control"
    - value : "public, must-revalidate, max-age=0"   ▿ 12 : 2 elements
    - key : "Date"
    - value : "Sun, 19 Aug 2018 18:36:49 GMT"

0 个答案:

没有答案