0

enter image description hereI have tried several ways to resolve this but may be I am missing something minor, or may be I am doing it completely wrong.

In a webView, I perform logon in a screen and after successful logon, it redirects to a URL like below

appevent://%7B%22accessToken%22:%22eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJDb2xydXl0LmVjdXN0b21lcm13IiwiaWF0IjoxNDgwNDExNjkwLCJuYmYiOjE0ODA0MTE1NzAsImV4cCI6MTQ4MDQyNjA5MCwic3ViIjoiQUN4dHJhLnVzZXI5NkB4dHJhLmNvbSIsImF1ZCI6WyJpemlhcHAiLCJlY3VzdG9tZXJtdyJdLCJjb2xyIjoiNTc5Mjk3MyJ9.FiZ-YYO30AI2xjgvkB3yt_nQTKMi4wSXZvATKWEpsx0KUkJEuExXXVIrUTWwMkukdH-mQkxKAo7WwjAE_rZ8_Y9DLTLor7xYkAF4g_EOiN0LZKa_zWtM9FJ3305BPp2oyTkUh1walyCuP_tCgr4L5iTvd0xlaObnc-WE6NtSzV--eTyteOqm1qfHjVZiR_OG8LWO0tzY7fvcVeEBc7gAO2Ki5Ytl7x0-ucvhGbTXWQot9gh4tJf4HwOyg19RWeFbkksQe3J1K0JY310yXTm079LpYMAnanNAvo_LUOHscZ5GdHlIYe4I4Wi60sKPJQmOrPYGztEUHWxG50HMW-mmcQ%22,%22refreshToken%22:%22eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJDb2xydXl0LmVjdXN0b21lcm13IiwiaWF0IjoxNDgwNDExNjkwLCJuYmYiOjE0ODA0MTE1NzAsImV4cCI6MTQ4MzA5MDA5MCwic3ViIjoieHRyYS51c2VyOTZAeHRyYS5jb20iLCJhdWQiOlsiaXppYXBwIiwiZWN1c3RvbWVybXciXSwiY29sciI6IjU3OTI5NzMifQ.a_-5Oi7dCDx6DOsQwPwA-M7UFtqfYzPDn5sTTxwlF8FfsmXLHoITXNuWNWKS3GmW4yr7x83USfFDbYXxq-xzsnj2bST1Vh9wxrLzXNX12z1VHyacdOYNuIBfhOLL0aj_5yCyKEnp614lCuqkEx473Cc-za-2wdvIi9RM5Fl4BGTtAXi-YnV-fOXvRlfUvnNEJ6cfggMVMcRxTgKIIzwDPl-d6OyPY4eFMllcbFYTnfqa5OYWadUM_IDU9nyjoriwEQbo80FdZbb3xru74-MZDPijab9Koi1I8uAhDE1G51BFOBukkPMojltibuTm-y_y_4ocuPux-GZH3Gp5KvOoUQ%22,%22loggedOn%22:true,%22customer%22:%7B%22cbhId%22:%2219139353%22,%22klantId%22:5792973,%22logonId%22:%22XTRA.USER96@XTRA.COM%22,%22status%22:3,%22statusCode%22:%22Confirmed%22,%22language%22:%22NL%22,%22title%22:%22Mr%22,%22firstName%22:%22Xtra-user%22,%22lastName%22:%2296%22,%22email%22:%22xtra.user96@xtra.com%22,%22emailLema%22:%22xtra.user96@xtra.com%22,%22dateOfBirth%22:%7B%22year%22:%221950%22,%22month%22:%2201%22,%22day%22:%2221%22%7D,%22robinsonPost%22:false,%22robinsonMail%22:false,%22privacyCustomer%22:false,%22address%22:%7B%22countryCode%22:%22BE%22,%22countryName%22:%22Belgi%EB%22,%22postalCode%22:%221500%22,%22locationName%22:%22HALLE%22,%22streetName%22:%22BERGENSESTEENWEG%22,%22houseNr%22:%22105%22,%22box%22:%221%22%7D,%22phones%22:%5B%7B%22telType%22:4,%22country%22:%2232%22,%22number%22:%2212345678%22,%22areaCode%22:%2212%22,%22subscribersNumber%22:%22345678%22,%22type%22:0%7D%5D%7D%7D

This URL, I am retrieving using "request" in webView shouldStartLoadWithRequest request: NSURLRequest

I don't have problems fetching this so far. Now I need to convert this to a dataObject so I can parse it as JSON and get the required values like "accessToken", "refreshToken" and other user related fields.

For that I am doing below -

public func webView(myWebView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let requestUrl:NSURL = request.URL!

//      let url:String = (requestUrl.absoluteString)!.stringByRemovingPercentEncoding! //App Crashes when there are special (French/Belgian) characters

        let url:String = (requestUrl.absoluteString)!.stringByReplacingOccurrencesOfString("%EB", withString: "%C3%AB").stringByRemovingPercentEncoding!   //Doing this to replace %EB to %C3%AB, otherwise app crashes

        if url.rangeOfString("appevent") != nil {      //Check if there is a token in the URL

            let index = url.rangeOfString("appevent://", options: .BackwardsSearch)?.endIndex

            let tokenObject = (url.substringFromIndex(index!))

            if let data = tokenObject.dataUsingEncoding(NSUTF8StringEncoding) {     //accessToken JSON object
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                    print(json)

                    if let accessTokenValue = json["accessToken"] as? String{
                        if let refreshTokenValue = json["refreshToken"] as? String {
                        print("\(accessTokenValue)")      
                        print("\(refreshTokenValue)")
                    }
                    }

                }

                catch {
                    print("Parsing went wrong")
                }
            }

        }
        else{
            print("No token in the URL")
        }

        return true
    }}   

I am manually replacing %EB with %C3%AB so that there is no problem with ë. I got this from SO link here
The problem/question is how do I do it for many other French/Belgian characters that could be present in my requestUrl? The app crashes if dont replace these special characters and I do not want to do that for every character since I can not guess what characters can come in.

I used stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) but with no luck.

Need help. Thanks in advance!

Community
  • 1
  • 1
Lohith Korupolu
  • 1,066
  • 1
  • 18
  • 52
  • Possible duplicate of [How to use special character in NSURL?](http://stackoverflow.com/questions/30148999/how-to-use-special-character-in-nsurl) – Eric Aya Nov 29 '16 at 12:41
  • Don't replace characters by hand, never! Use one of the predefined methods for doing this. – Eric Aya Nov 29 '16 at 12:42
  • @EricAya: I directly get the percentage encoded string in the request. And am not able to further remove the percentages due to the presence of these special characters – Lohith Korupolu Nov 29 '16 at 13:06
  • Have you tried removing the encoding before doing anything else? Like this: http://stackoverflow.com/a/38345778/2227743 But seriously, anyway, don't use stringByReplacingOccurrencesOfString for this kind of task. :) – Eric Aya Nov 29 '16 at 13:08
  • Yes, I tried that first. It's there in my question but commented. It didn't work though. – Lohith Korupolu Nov 29 '16 at 13:22
  • @EricAya: Please check the screenshot I added in my question – Lohith Korupolu Nov 29 '16 at 14:10

1 Answers1

1

I am answering my own question, used stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding).

Here is my full code:

public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let requestUrl = request.URL?.absoluteString?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    print("The actual request \(requestUrl)")


    //let url:String = (requestUrl.absoluteString)!.stringByReplacingOccurrencesOfString("%EB", withString: "%C3%AB").stringByRemovingPercentEncoding!   //Temporary Until Encoding issue is fixed

    if let url = requestUrl {

        if url.rangeOfString("appevent") != nil {      //Check if there is a token in the URL

            let index = url.rangeOfString("appevent://", options: .BackwardsSearch)?.endIndex

            let tokenObject = (url.substringFromIndex(index!))

            if let data = tokenObject.dataUsingEncoding(NSUTF8StringEncoding) {     //accessToken JSON object
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                    print(json)

                    if let accessTokenValue = json["accessToken"] as? String{
                        if let refreshTokenValue = json["refreshToken"] as? String {
                            print("\(accessTokenValue)")   
                             print("\(refreshTokenValue)")

                }

                catch {
                    print("Parsing Went Wrong")
                }
            }

        }
        else {
            print("No token in the URL")
        }
    }

    else {
        print("URL Not handled")
    }

    return true
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Lohith Korupolu
  • 1,066
  • 1
  • 18
  • 52
  • 1
    yes. stringByRemovingPercentEncoding never worked. stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding). worked for me – Lohith Korupolu Nov 30 '16 at 13:17
  • Oh, ok. I didn't notice the difference, sorry. Well, I wonder why stringByRemovingPercentEncoding does not work in this case! – Eric Aya Nov 30 '16 at 13:18