Encode the url in Swift - ios

This is my url,
http://api.theahsanzaman.info/token?username=haris123#gmail.com&password=Haris#123&grant_type=password
I want it to encode it like this way,
http://api.theahsanzaman.info/token?username%3Dharis123%40gmail.com%26password%3DHaris%40123%26grant_type%3Dpassword
The = sign should be replace by %3D
The & sign should be replace by %26
The # sign should be replace by %40
How can i change my ur to this?

If you want to do that, remove the characters to be percent escaped from the .urlQueryAllowed character set and percent encode accordingly:
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "=#&")
let result = urlString.addingPercentEncoding(withAllowedCharacters: allowed)

Related

encode url swift withAllowedCharacters not working encoding %20 as %2520 (means encoding % as %25)

Following is my code for URL encoding
extension String {
var encoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
}
}
But I am facing issue if url contains %20. it is encoding it as %2520 although I have added urlQueryAllowed
Original url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG
Encoded url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%2520Coffee%2520Vending%2520Machine.JPG
If you have an already encoded URL String, you first need to remove percent encoding before applying it again.
If you aren't sure whether the URL you have is already encoded or not, you can simply use an if let on removingPercentEncoding and depending on its result, either call addingPercentEncoding on the original URL or on the one that you removed the encoding from.
let alreadyEncodedURLString = "https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG"
if let unencodedURLString = alreadyEncodedURLString.removingPercentEncoding {
unencodedURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
} else {
alreadyEncodedURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}

Swift URL.path changes encoding of utf-8 characters

Why does converting a String to an URL in Swift 4.2 and then converting the URL back to a String using url.path change the encoding of special characters like german umlauts (ä, ö, ü), even if I use a utf-8 encoding?
I wrote some sample code to show my problem. I encoded the strings to base64 in order to show that there is a difference.
I also have a similar unsolved problem with special characters and swift here.
Sample Code
let string = "/path/to/file"
let stringUmlauts = "/path/to/file/with/umlauts/testäöü"
let base64 = Data(string.utf8).base64EncodedString()
let base64Umlauts = Data(stringUmlauts.utf8).base64EncodedString()
print(base64, base64Umlauts)
let url = URL(fileURLWithPath: string)
let urlUmlauts = URL(fileURLWithPath: stringUmlauts)
let base64Url = Data(url.path.utf8).base64EncodedString()
let base64UrlUmlauts = Data(urlUmlauts.path.utf8).base64EncodedString()
print(base64Url, base64UrlUmlauts)
Output
The base64 and base64Url string stay the same but the base64Umlauts and the base64UrlUmlauts are different.
"L3BhdGgvdG8vZmlsZQ==" for base64
"L3BhdGgvdG8vZmlsZQ==" for base64Url
"L3BhdGgvdG8vZmlsZS93aXRoL3VtbGF1dHMvdGVzdMOkw7bDvA==" for base64Umlauts
"L3BhdGgvdG8vZmlsZS93aXRoL3VtbGF1dHMvdGVzdGHMiG/MiHXMiA==" for base64UrlUmlauts
When I put the base64Umlauts and base64UrlUmlauts strings into an online Base64 decoder, they both show /path/to/file/with/umlauts/testäöü, but the ä, ö, ü are different (not visually).
stringUmlauts.utf8 uses the Unicode characters äöü.
But urlUmlauts.path.utf8 uses the Unicode characters aou each followed by the combining ¨.
This is why you get different base64 encoding - the characters look the same but are actually encoded differently.
What's really interesting is that Array(stringUmlauts) and Array(urlUmlauts.path) are the same. The difference doesn't appear until you perform the UTF-8 encoding of the otherwise exact same String values.
Since the base64 encoding is irrelevant, here's a more concise test:
let stringUmlauts = "/path/to/file/with/umlauts/testäöü"
let urlUmlauts = URL(fileURLWithPath: stringUmlauts)
print(stringUmlauts, urlUmlauts.path) // Show the same
let rawStr = stringUmlauts
let urlStr = urlUmlauts.path
print(rawStr == urlStr) // true
print(Array(rawStr) == Array(urlStr)) // true
print(Array(rawStr.utf8) == Array(urlStr.utf8)) // false!!!
So how is the UTF-8 encoding of two equal strings different?
One solution to this is to use precomposedStringWithCanonicalMapping on the result of path.
let urlStr = urlUmlauts.path.precomposedStringWithCanonicalMapping
Now you get true from:
print(Array(rawStr.utf8) == Array(urlStr.utf8)) // now true

NSURL - encode '&' with spaces

Currently i am using the following way to encode the url
urlAndMethod.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
After encoding
http://103.50.154.52:8383/api/master/insta-list?category=Postpaid%20Mobile%20CDMA%20&%20Landline
How do i handle the special characters including '&'
You can use .urlHostAllowed characterset.
let escapedString = someString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Can iOS URL support unicode characters within top level domain?

I'm building an iOS app that takes urls as input.
Unicode characters are valid for a tld but when I instantiate a valid URL that contains unicode characters NSURL returns nil.
Is this even possible?
swift eg.
URL(string: "http://➡.ws/䨹")
How to use special characters in URL (Swift 3) :
let myUrl = "http://➡.ws/䨹" as String
let url = URL(string: myUrl) // nil here .. problem !
if let encoded = myUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed){
let urlencoded = URL(string: encoded) // "http://%E2%9E%A1.ws/%E4%A8%B9" here :) no problem ^^
}

NSUrl swift 2 with greek and other special characters

I'm trying to make a server request with
NSUrl(string: "http://example.com/α")
In which α is a greek character. So when i request this i get an error and my app crashes. So i tried to encode the url to this
let myUrl = NSURL(string: myLink.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!
and now my link has become http://example.com/%CE%B1
where %CE%B1 is the α character. Although my server does not recognise it and it doesnt send me back the data.
I use node.js with io.socket connections. Is there any way with swift to send the correct url without the percent encoding?
For encode α in your url
let str = "α"
let url = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
Now decode url string like this
let orgStr = url?.stringByRemovingPercentEncoding
print(orgStr)

Resources