Swift stringByRemovingPercentEncoding带有重音字符的问题,例如ë

时间:2016-11-29 10:38:59

标签: ios uiwebview swift2 percent-encoding

enter image description here我已经尝试了几种方法来解决这个问题,但可能是我错过了一些小问题,或者我可能完全错了。

在webView中,我在屏幕上执行登录,成功登录后,它会重定向到如下所示的网址

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

此网址,我正在使用webView shouldStartLoadWithRequest request: NSURLRequest

中的“请求”进行检索

到目前为止,我没有遇到任何问题。现在我需要将其转换为dataObject,以便我可以将其解析为JSON并获取所需的值,如“accessToken”,“refreshToken”和其他用户相关字段。

为此,我在下面做 -

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

我手动将%EB替换为%C3%AB,以便ë没有问题。我从SO link here得到了这个 问题/问题我如何为我的requestUrl中可能出现的许多其他法语/比利时字符执行此操作? 如果不替换这些特殊字符,应用程序崩溃,我不想为每个字符都这样做,因为我无法猜出哪些字符可以进来。

我使用stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())但没有运气。

需要帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

我正在回答我自己的问题,使用stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

这是我的完整代码:

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
}