Search code examples
iosswiftuiwebview

Adding custom http header field on all UIWebView requests


I'm using the below code to set a custom HTTP header on requests sent from my UIWebView. The problem is that I'm seeing the page load for a second and then it goes to a white/blank screen. I've tested with different URLs but the behavior is the same. Any ideas?

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

        if headerIsPresent {
            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
        }
    }

Solution

  • Based on David's comments, I used the following solution:

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