```stringByAddingPercentEncodingWithAllowedCharact...
# multiplatform
r
Copy code
stringByAddingPercentEncodingWithAllowedCharacters
doesn’t work on Kotlin Native. My code is like following:
Copy code
actual fun urlEncode(url: String) : String {
    val set = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as NSMutableCharacterSet
    set.addCharactersInString("+&")
    return NSString.create(string=url).stringByAddingPercentEncodingWithAllowedCharacters(
        allowedCharacters = NSCharacterSet.URLQueryAllowedCharacterSet()
    ) ?: ""
}
My test code:
Copy code
@Test
fun testUrlEncode() {
    assertEquals(
        "https%3A%2F%2Fmontageapps.com%3Ftoken%3Drth%26price%3Dinvaluable",
        urlEncode("<https://montageapps.com?token=rth&price=invaluable>")
    )
}
Test result:
kotlin.AssertionError: Expected <https%3A%2F%<http://2Fmontageapps.com|2Fmontageapps.com>%3Ftoken%3Drth%26price%3Dinvaluable>, actual <<https://montageapps.com?token=rth&price=invaluable>>.
a
Hi, @Ran! To make the test work, I changed your function as follows:
Copy code
fun urlEncode(url: String) : String {
    val set = NSCharacterSet.letterCharacterSet().mutableCopy() as NSMutableCharacterSet
    set.addCharactersInString(".")
    return NSString.create(string=url).stringByAddingPercentEncodingWithAllowedCharacters(
        allowedCharacters = set
    ) ?: ""
}
r
Thanks, maybe we should figure out that why
NSCharacterSet.URLQueryAllowedCharacterSet
doesn’t work
a
I would say this is because this set contains symbols you want to be encoded. Can’t find a way to print this set’s contents right now, unfortunately, but you might want to check it by yourself.