Swift - encode URL
Swift 3
In Swift 3 there is addingPercentEncoding
let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)
Output:
test%2Ftest
Swift 1
In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters
var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")
Output:
test%2Ftest
The following are useful (inverted) character sets:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
If you want a different set of characters to be escaped create a set:
Example with added "=" character:
var originalString = "test/test=42"
var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")
Output:
test%2Ftest%3D42
Example to verify ascii characters not in the set:
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 Encode Custom String to populate URL
Your parameters needs to be url encoded.
You can use URLComponents to create your URL
and pass your parameters as URLQueryItem
instances, like that:
let productSearchString = "iphone 12"
var urlComponents = URLComponents(string: "https://test@api.search")
urlComponents?.queryItems = [
URLQueryItem(name: "query", value: productSearchString),
URLQueryItem(name: "limit", value: "1")
]
let url = urlComponents?.url
print(url?.absoluteString ?? "nil") // https://test@api.search?query=iphone%2012&limit=1
URL Encoding of String accepting all special characters in swift
Thank you @MartinR and @benleggiero for : How do I URL encode a string
It helped a lot.
It was not including all special characters.
Checked one by one and added those which were missing as below:
extension CharacterSet {
public static let urlQueryParameterAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&?~!$*(.,)_-+':"))
public static let urlQueryDenied = CharacterSet.urlQueryAllowed.inverted()
public static let urlQueryKeyValueDenied = CharacterSet.urlQueryParameterAllowed.inverted()
public static let urlPathDenied = CharacterSet.urlPathAllowed.inverted()
public static let urlFragmentDenied = CharacterSet.urlFragmentAllowed.inverted()
public static let urlHostDenied = CharacterSet.urlHostAllowed.inverted()
public static let urlDenied = CharacterSet.urlQueryDenied
.union(.urlQueryKeyValueDenied)
.union(.urlPathDenied)
.union(.urlFragmentDenied)
.union(.urlHostDenied)
public func inverted() -> CharacterSet {
var copy = self
copy.invert()
return copy
}
}
Related Topics
Take Screenshots in the iOS Simulator
How to Develop or Migrate Apps For Iphone 5 Screen Resolution
Getting the Difference Between Two Dates (Months/Days/Hours/Minutes/Seconds) in Swift
How to Present Uialertcontroller When Not in a View Controller
How to Create a Basic Uibutton Programmatically
Is [Uiscreen Mainscreen].Bounds.Size Becoming Orientation-Dependent in Ios8
How to Install iOS 6 Sdk on Xcode 5
How to Customize the Background/Border Colors of a Grouped Table View Cell
How to Change Image Tintcolor in iOS and Watchkit
Impact of Xcode Build Options "Enable Bitcode" Yes/No
How to Show Verification Code Suggestion on Keyboard from Message
How to Deal With the Nsdateformatter Locale "Feechur"
Opening the Settings App from Another App
Number of Days Between Two Nsdates