为所有UIWebView请求添加自定义HTTP标头字段

时间:2017-07-18 17:28:04

标签: ios swift webview header http-headers

我使用以下代码为从我的UIWebView发送的请求设置自定义HTTP标头。使用swift3编码时出现语法错误 是否可以使用swift3进行修改?

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let headerFields = request.allHTTPHeaderFields
    var headerIsPresent = contains(request.allHTTPHeaderFields?.keys.array as [String], "X-Test-App")

    if headerIsPresent || navigationType == UIWebViewNavigationType.Other {
        return true
    } else {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            dispatch_async(dispatch_get_main_queue(), {
                let url = request.URL
                var newRequest: NSMutableURLRequest = request as NSMutableURLRequest
                // set new header
                newRequest.addValue("MyValue", forHTTPHeaderField: "X-Test-App")

                // reload the request
                self.webView.loadRequest(newRequest)
            })
        })
        return false
    }
}

0 个答案:

没有答案