Created
November 6, 2015 23:29
-
-
Save Ben-G/9f3d9c96afd680ee93f7 to your computer and use it in GitHub Desktop.
URL Encoded String Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct URLEncodedString { | |
private (set) var encodedString: String | |
init(_ string: String) { | |
self.encodedString = URLEncodedString.URLEncode(string) | |
} | |
// Based on Alamofire Parameter Encoding: https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift | |
static func URLEncode(string: String) -> String { | |
let generalDelimiters = ":#[]@ " // does not include "?" or "/" due to RFC 3986 - Section 3.4 | |
let subDelimiters = "!$&'()*+,;=" | |
let allowedCharacters = generalDelimiters + subDelimiters | |
let customAllowedSet = NSCharacterSet(charactersInString:allowedCharacters).invertedSet | |
let escapedString = string.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)! | |
return escapedString | |
} | |
} | |
extension URLEncodedString: StringLiteralConvertible { | |
var description: String { | |
get { | |
return encodedString | |
} | |
} | |
} | |
extension URLEncodedString: CustomStringConvertible { | |
init(stringLiteral value: String) { | |
self.init(value) | |
} | |
init(extendedGraphemeClusterLiteral value: String) { | |
self.init(value) | |
} | |
init(unicodeScalarLiteral value: String) { | |
self.init(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment