iOS 中的 URL 解码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32974795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:55:52  来源:igfitidea点击:

URL decode in iOS

iosswifturldecode

提问by JibW

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

我正在使用 Swift 1.2 来开发我的 iPhone 应用程序,并且我正在与一个 http Web 服务进行通信。

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

我得到的响应是查询字符串格式(键值对)和以.Net.

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

我可以得到响应,但正在寻找使用 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?

如何替换字符串中的所有 URL 转义字符?

回答by Vyacheslav

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

要对 url 进行编码和解码,请在项目中的某处创建此扩展名:

Swift 2.0

斯威夫特 2.0

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

}

Swift 3.0

斯威夫特 3.0

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

    }

Swift 4.1

斯威夫特 4.1

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

回答by u5150587

Swift 2 and later (Xcode 7)

Swift 2 及更高版本 (Xcode 7)

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

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

let sDecode = sEncode?.stringByRemovingPercentEncoding

回答by matt

The stringByReplacingEscapesUsingEncodingmethod 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.

stringByReplacingEscapesUsingEncoding方法行为正确。该"+"字符不是百分比编码的一部分。该服务器使用不当;它应该在此处使用百分比转义空格 ( %20)。如果对于特定的响应,您想要在其中看到"+"字符的空间,您只需像您已经在做的那样,通过自己执行替换来解决服务器行为。

回答by Cai?ara

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:

就我而言,我需要在查询字符串参数中的电话号码中添加加号(“+”)信号,例如“+55 11 99999-5555”。在我发现 swift3 (xcode 8.2) 编码器不会将“+”编码为加号信号,而是将空格编码为空格后,我不得不在编码后寻求解决方法:

Swift 3.0

斯威夫特 3.0

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

回答by Amul4608

In Swift 3

在斯威夫特 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)" )

回答by nikans

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

最好使用内置URLComponents结构,因为它遵循适当的准则。

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

回答by ScottyBlades

You only need:

你只需要:

print("Decode: ", yourUrlAsString.removingPercentEncoding)