Search code examples
swiftnsurluiapplicationimessage

Opening iMessage with default body containing a link


I am trying to open up the iMessage app with a default message from my app. The default message contains a link to the app in the app store. This is used as a way for users to invite people to download the app.

The user types in a number and then hits a submit button and then it opens up the iMessage app with that number and a refilled message. However, for some reason, Swift won't generate the URL. Here is what I have

let body = "Download SomeApp by clicking the link below:\n\nhttps://appsto.re/us/someapp.i"

guard let phoneUrl = URL(string: "sms:\(numberTextField.text!)&body=\(body)") else {
            return
}

if UIApplication.shared.canOpenURL(phoneUrl) {
    UIApplication.shared.open(phoneUrl, options: [:], completionHandler: nil)
}

Right now its not even getting past the guard statement.

All I want to do is open iMessage with a link to my app in the body.


Solution

  • You need to escape the content passed into the &body= parameter. You can do this with addingPercentEncoding.

    For example:

    let body = "Download SomeApp by clicking the link below:\n\nhttps://appsto.re/us/someapp.i"
    
    guard let escapedBody = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
        return
    }
    
    guard let phoneUrl = URL(string: "sms:\(numberTextField.text!)&body=\(escapedBody)") else {
        return
    }