I am running the code from similar questions from stackoverflow to percentage encode only all the special characters(@!#$%^&*()~-_= ;:'/.,<>{}[])(not encoding alphanumeric characters) on xcode playground . Here are my attempts
import UIKit
//////////////
//Attempt 1
var originalString = "Test@123!#$%^&*()~-_= ;:'/.,<>{}[]"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
print("Attemp 1:",escapedString)
///////////////////
//Attempt 2
func encodeValue(_ string: String) -> String? {
guard let unescapedString = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":/").inverted) else { return nil }
return unescapedString
}
let encodedString = encodeValue("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
print("Attemp 2:",encodedString)
//////////////////////
//Attempt 3
extension String {
var encoded: String? {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
}
}
let encodedUrl = "Test@123!#$%^&*()~-_= ;:'/.,<>{}[]".encoded
print("Attemp 3:",encodedUrl)
//////////////
//Attempt 4
let myurlstring = "Test@123!#$%^&*()~-_= ;:'/.,<>{}[]"
let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
print("Attemp 4:",urlwithPercentEscapes)
//////////////
//Attempt 5
var s = "Test@123!#$%^&*()~-_= ;:'/.,<>{}[]"
let encodedLink = s.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
let encodedURL = NSURL(string: encodedLink!)! as URL
print("Attemp 5:",encodedURL)
Here are the results
Attemp 1: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 2: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 3: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 4: Optional("Test@123!#$%^&*()~-_= ;:'/.,<>{}[]")
Attemp 5: Test@123!#$%^&*()~-_= ;:'/.,<>{}[]
Non of them are percentage encoding the complete special characters.I want to encode all of the special character just like following special character are never encoded in almost all attempts.
*()~-_= ;:'/.,
Kindly tell me the code to percentage encode all of my special character including *()~-_= ;:'/., ? Thanks
CodePudding user response:
To percent-encode everything except alphanumerics, pass .alphanumerics
as the allowed characters:
let encoded = s.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
For your example this returns (as an Optional):
Test@123!#$%^&*()~-_=+;:'/.,<>{}[]
I assume this what you were looking for.
This isn't particularly useful, since this is unlikely to correctly encode any particular URL (which is what you seem to be doing). But if you have the need you describe (which is unrelated to correctly encoding URLs), then that's how you do it.
If you want to correctly encode URLs, construct the URL using URLComponents. It'll encode each piece using the rules for that piece. There is no simple string substitution that will correctly percent-encode an URL.