URL resource links containing an apostrophe (') do not open

Hello,

I noticed that links containing an apostrophe will return nil. I have provided an example below. Does anyone have a workaround or solution for this problem?


//Code...
item.url = "https://www.robinrendle.com/notes/i-don't-believe-in-sprints/"

.onTapGesture {
  guard let url = URL(string: "\(item.url)") else { return }
  UIApplication.shared.open(url)
}

printing URL(string: "(item.url)") will return a nil.

Answered by robnotyou in 731438022

If ' appears in a URL, it must be url-encoded.

  • For ' try %27

For more info, see https://www.w3schools.com/tags/ref_urlencode.asp

Accepted Answer

If ' appears in a URL, it must be url-encoded.

  • For ' try %27

For more info, see https://www.w3schools.com/tags/ref_urlencode.asp

Swift example of how to fix this:


extension String {

    var urlEncoded: String? {

        let allowedCharacterSet = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "~-_."))

        return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)

    }

}
print("https://www.robinrendle.com/notes/i-don't-believe-in-sprints/".urlEncoded!) 
// prints https%3A%2F%2Fwww.robinrendle.com%2Fnotes%2Fi-don%27t-believe-in-sprints%2F

Credit to: https://stackoverflow.com/questions/24551816/swift-encode-url

What OS/version is this happening on? I just tried it on iOS 16 simulator and the REPL in Monterey, and the URL gets created successfully.

However, while unencoded apostrophe works (at least on these versions) indeed it’s a best practice to encode it.

But that still won’t work in your specific example, because the URL of your actual page uses a curly quote (U+2019 RIGHT SINGLE QUOTATION MARK in Unicode-speak). That character also works unencoded, or is more properly encoded as %E2%80%99.

Probably an even better practice would be to manually remove this character from the URL (which is obviously derived from the page title) if you have control over that.