Modify URL Before Loading Request in UIWebView

我是研究僧i 提交于 2019-12-22 19:49:52

问题


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.



来源:https://stackoverflow.com/questions/32253997/modify-url-before-loading-request-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!