Encoding Url Using Swift Code

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)\'")
}

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

URL in diffrent Language, How to convert a URL in Swift?

See my answer here https://stackoverflow.com/a/49492592/4601900

You need to encode it Because your last path component is not looks like plain string

let testurl = "http://example.com/ΥΠΗΡΕΣΙΕΣ.jpg"

if let encodedURL = testurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedURL) {
print("valid url")

} else {
print("invalid url ")
}

Ouptut

valid url

If your print your encodedURL you will get // Here if you print encoded url you will get
http://example.com/%CE%A5%CE%A0%CE%97%CE%A1%CE%95%CE%A3%CE%99%CE%95%CE%A3.jpg

Swift Encoding data into a URL

Yes, that's trivial, and there's nothing special about Swift or iOS involved in doing it.

Set up your URL to be a URL that points to your website, with a query parameter that passes the desired data:

http://mywebsite/loaddata?code=aabbccddeeffgghhiijjkkllmmnn

You could encode the data as Base64 encoded output from the encryption algorithm of your choice, so only your apps would be able to decode it.

Encode that as the string in your QR code. Most QR code readers recognize HTTP URLs and will offer to open the link.

You would then code your website to respond to the URL as desired.

Your app could be coded to parse the string from the QR code and ignore everything but the part after the code=.

URLencoding in swift

Thank you, Rob, that answers helped me.

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = postParameters.map { key, value in
let keyString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
let valueString = (value as! String).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
return keyString + "=" + valueString
}.joined(separator: "&").data(using: .utf8)

and extension

extension CharacterSet {

static var urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="

var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

return allowed
}()
}


Related Topics



Leave a reply



Submit