How to know if a string is already escaped special with special characters?

Viewed 1089

I have this URL:

"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

3 Answers

you can do it smoothly:

extension String {
    func isEscaped() -> Bool {
        return self.removingPercentEncoding != self
    }
}

then

let yourEscapedString = "http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg"
print(yourEscapedString.isEscaped()) // true

let yourNotEscapedString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
print(yourNotEscapedString.isEscaped()) // false

I don't know but might be work.

You can check your URL is valid or not, If Its valid then no need to escaping agin if not then you should escape it.

Like check URL is valid or not

func isValidMyURL (_ urlString: NSString) -> Bool {
    let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
    return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString)
}

And then

if !isValidMyURL(originalString) { // If not valid then escape it
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}

Other wise directly use escapedString.

I am not able to test this, but I would try to 'unescape' the original string first, and then compare the result with the original string. If they match, there was no escaping in the original string. If they don't match, the original string was escapeds already.

Related