Modify URL Before Loading Request in UIWebView

2019-05-28 20:48发布

问题:

I created a native app from my web app using UIWebView.

My webapp is a basic CMS with some static pages, some category pages and and some detail pages.

Now I need to check if the request comes from the web app or the native app.

To do this I have two possibilities:

First solution: Modify URL and check URL on server side:

@IBOutlet var WebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    loadWebPage()
}

func loadWebPage() {
    let url = NSURL(string: "http://localhost:8888?apptype=native")
    let request = NSURLRequest(URL: url!) 
    WebView.loadRequest(request)
}

When I check on server side if the the parameter exists on the first page it works, but when I switch to other pages (categories etc.) the condition fails.

Second solution: I tried to set cookies:

@IBOutlet var WebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    loadWebPage()
}

func loadWebPage() {
    let url = NSURL(string: "http://localhost:8888")
    let request = NSURLRequest(URL: url!)

    var cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as! [NSHTTPCookie]

    var reqCookies:[AnyObject] = []

    for aCookie in cookies {

        reqCookies += [aCookie]

    }

    var headers = NSHTTPCookie.requestHeaderFieldsWithCookies(reqCookies)

    WebView.loadRequest(request)
}

But how do I add cookies in this example in the response so I can retrieve them on server side?

Are there any other solutions or how can I modify my existing ones?

回答1:

Implement the UIWebViewDelegate method webView:shouldStartLoadWithRequest:navigationType:.

When the user taps a link in the webview, this delegate method is called. Take the request.url of NSURLRequest passed into the delegate method and create a new NSURLRequest with ?apptype=native appended to the request.url property.