Swift – 编码URL

如果我编码像这样的string:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 

它不会逃避斜杠/

我已经search并find了这个Objective C代码:

 NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)unencodedString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ); 

有一个更简单的方法来编码的url,如果不是,我怎么写在Swift?

Swift 3

在Swift 3中addingPercentEncoding

 var originalString = "test/test" var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) print(escapedString!) 

输出:

testing%2Ftest

斯威夫特1

在iOS 7及以上,有stringByAddingPercentEncodingWithAllowedCharacters

 var originalString = "test/test" var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) println("escapedString: \(escapedString)") 

输出:

testing%2Ftest

以下是有用的(反转)字符集:

 URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^` 

如果你想要不同的字符集转义创build一个集合:
添加“=”字符的示例:

 var originalString = "test/test=42" var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) println("escapedString: \(escapedString)") 

输出:

testing%2Ftest%3D42

validation不在集合中的ascii字符的示例:

 func printCharactersInSet(set: NSCharacterSet) { var characters = "" let iSet = set.invertedSet for i: UInt32 in 32..<127 { let c = Character(UnicodeScalar(i)) if iSet.longCharacterIsMember(i) { characters = characters + String(c) } } print("characters not in set: \'\(characters)\'") } 

Swift 3:

 let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted) if let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) { //do something with escaped string } 

您可以使用URLComponents来避免手动百分号转义您的查询string:

 let scheme = "https" let host = "www.google.com" let path = "/search" let queryItem = URLQueryItem(name: "q", value: "Formula One") var urlComponents = URLComponents() urlComponents.scheme = scheme urlComponents.host = host urlComponents.path = path urlComponents.queryItems = [queryItem] if let url = urlComponents.url { print(url) // "https://www.google.com/search?q=Formula%20One" } 

 extension URLComponents { init(scheme: String, host: String, path: String, queryItems: [URLQueryItem]) { self.init() self.scheme = scheme self.host = host self.path = path self.queryItems = queryItems } } if let url = URLComponents(scheme: "https", host: "www.google.com", path: "/search", queryItems: [URLQueryItem(name: "q", value: "Formula One")]).url { print(url) // https://www.google.com/search?q=Formula%20One } 

一切都是一样的

 var str = CFURLCreateStringByAddingPercentEscapes( nil, "test/test", nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue ) // test%2Ftest 

Swift 3:

 let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师" 

1. encodingQuery:

 let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed) 

结果:

 "http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 

2. encodingURL:

 let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) 

结果:

 "http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 

Swift 3

 let allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed.remove(charactersIn: ";/?:@&=+$, ") paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) 

Swift 2.2 (从Zaph中借用并更正url查询键和参数值)

 var allowedQueryParamAndKey = NSCharacterSet(charactersInString: ";/?:@&=+$, ").invertedSet paramOrKey.stringByAddingPercentEncodingWithAllowedCharacters(allowedQueryParamAndKey) 

例:

 let paramOrKey = "https://some.website.com/path/to/page.srf?a=1&b=2#top" paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) // produces: "https%3A%2F%2Fsome.website.com%2Fpath%2Fto%2Fpage.srf%3Fa%3D1%26b%3D2%23top" 

这是布赖恩·陈的答案的一个更短的版本。 我猜想urlQueryAllowed是允许控制字符,通过它是好的,除非他们形成键或值的一部分,在您的查询string,他们需要逃脱。

自己需要这个,所以我写了一个String扩展,它既允许URLEncodingstring,也允许更常见的最终目标,将参数字典转换为“GET”风格的URL参数:

 extension String { func URLEncodedString() -> String? { var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) return escapedString } static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? { if (parameters.count == 0) { return nil } var queryString : String? = nil for (key, value) in parameters { if let encodedKey = key.URLEncodedString() { if let encodedValue = value.URLEncodedString() { if queryString == nil { queryString = "?" } else { queryString! += "&" } queryString! += encodedKey + "=" + encodedValue } } } return queryString } } 

请享用!

这个正在为我工​​作。

 func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? { let unreserved = "*-._" let allowed = NSMutableCharacterSet.alphanumericCharacterSet() allowed.addCharactersInString(unreserved) if plusForSpace { allowed.addCharactersInString(" ") } var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed) if plusForSpace { encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+") } return encoded } 

我从这个链接find上面的函数: http : //useyourloaf.com/blog/how-to-percent-encode-a-url-string/ 。