0

I have a string that can include any characters, from alphanumeric to special chars like "&,.:/!" etc. I need to encode that string and send it to twitter. I tried the following but as soon as theres an & character in text, it doesn't work properly:

static func shareToTwitter(text: String) {
    guard let urlEscaped = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
        return
    }
    guard let url = URL(string: "twitter://post?message=\(urlEscaped)") else {
        return
    }
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
    } else {
        guard let twitterUrl = URL(string: "https://twitter.com/intent/tweet?text=\(urlEscaped)") else {
            return
        }
        UIApplication.shared.open(twitterUrl)
    }
}

So an example sentence might be: "I'm here & there". Instead, Twitter will receive "I'm here". How can I fix this?

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • Take a look at this article [How to percent encode a URL String](https://useyourloaf.com/blog/how-to-percent-encode-a-url-string/) ... looks like it should solve the issue. – DonMag Sep 02 '21 at 16:00
  • 1
    You shouldn't use string interpolation to build URLs, for exactly this reason. Use [`URLComponents`](https://developer.apple.com/documentation/foundation/urlcomponents). – Alexander Sep 02 '21 at 16:14

1 Answers1

2

As suggested by Alexander the most reliable way is to use URLComponents and URLQueryItem

static func shareToTwitter(text: String) {
    var components = URLComponents(string: "twitter://post")!
    components.queryItems = [URLQueryItem(name: "message", value: text)]
    if let url = components.url, UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
    } else {
        components = URLComponents(string: "https://twitter.com/intent/tweet")!
        components.queryItems = [URLQueryItem(name: "text", value: text)]
        guard let twitterUrl = components.url else { return }
        UIApplication.shared.open(twitterUrl)
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    Is the `UIApplication.shared.canOpenURL(url)` check necessary? (I know the OP had it in their code and you just kept it, but I'm trying to see what it's supposed to do) – Alexander Sep 02 '21 at 16:50
  • 1
    Frankly I don't know what the OP is going to accomplish. – vadian Sep 02 '21 at 16:51
  • @Alexander Yes the `canOpenURL` IS necessary because if the user doesn't have the twitter app installed it won't be able to open that link. Therefore I need to fall back to the web. – Tometoyou Sep 02 '21 at 17:23
  • @Tometoyou Oh i just noticed that the scheme is `twitter://`. This makes sense! – Alexander Sep 02 '21 at 17:45