URL decode in iOS

本小妞迷上赌 提交于 2019-12-03 06:23:30

问题


I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.

The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.

I can get the response, but looking the proper way to decode using Swift.

Sample response is as follows

status=1&message=The+transaction+for+GBP+12.50+was+successful

Tried following way to decode and get the server response

// This provides encoded response String
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)!

How can I replace all URL escaped characters in the string?


回答1:


To encode and decode urls create this extention somewhere in the project:

Swift 2.0

extension String
{   
    func encodeUrl() -> String
    {
        return self.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
    }
func decodeUrl() -> String
    {
        return self.stringByRemovingPercentEncoding
    }

}

Swift 3.0

 extension String
    {   
        func encodeUrl() -> String
        {
            return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
        }
    func decodeUrl() -> String
        {
            return self.removingPercentEncoding
        }

    }

Swift 4.1

extension String
{
    func encodeUrl() -> String?
    {
        return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
    }
    func decodeUrl() -> String?
    {
        return self.removingPercentEncoding
    }
}



回答2:


Swift 2 and later (xCode 7)

var s = "aa bb -[:/?&=;+!@#$()',*]";

let sEncode = s.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

let sDecode = sEncode?.stringByRemovingPercentEncoding



回答3:


The stringByReplacingEscapesUsingEncoding method is behaving correctly. The "+" character is not part of percent-encoding. This server is using it incorrectly; it should be using a percent-escaped space here (%20). If, for a particular response, you want spaces where you see "+" characters, you just have to work around the server behavior by performing the substitution yourself, as you are already doing.




回答4:


In my case, I NEED a plus ("+") signal in a phone number in parameters of a query string, like "+55 11 99999-5555". After I discovered that the swift3 (xcode 8.2) encoder don't encode "+" as plus signal, but space, I had to appeal to a workaround after the encode:

Swift 3.0

_strURL = _strURL.replacingOccurrences(of: "+", with: "%2B")



回答5:


In Swift 3

extension URL {
    var parseQueryString: [String: String] {
        var results = [String: String]()

        if let pairs = self.query?.components(separatedBy: "&"),  pairs.count > 0 {
            for pair: String in pairs {
                if let keyValue = pair.components(separatedBy: "=") as [String]? {
                    results.updateValue(keyValue[1], forKey: keyValue[0])
                }
            }
        }
        return results
    }
}

in your code to access below

let parse = url.parseQueryString
        print("parse \(parse)" )



回答6:


It's better to use built-in URLComponents struct, since it follows proper guidelines.

extension URL
{
    var parameters: [String: String?]?
    {
        if  let components = URLComponents(url: self, resolvingAgainstBaseURL: false), 
            let queryItems = components.queryItems
        {
            var parameters = [String: String?]()
            for item in queryItems {
                parameters[item.name] = item.value
            }
            return parameters
        } else {
            return nil
        }
    }
}


来源:https://stackoverflow.com/questions/32974795/url-decode-in-ios

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