How can I programmatically compose a message?

2019-06-20 10:20发布

问题:

How can I open the Messages app on the compose screen, with the message body preloaded with specific text?

回答1:

Benjy's answer is almost correct, but has one issue.

Since urlSafeBody isn't unwrapped, string interpolation yields

sms:&body=Optional("Hello%20World!")

which is causing NSURL initialization to return nil, since the URL string is malformed.

Here's a working example which conditionally unwraps optionals. This removes any possibility of crashes related to nil optionals being force-unwrapped.

let messageBody = "Hello World!"
let urlSafeBody = messageBody.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
if let urlSafeBody = urlSafeBody, url = NSURL(string: "sms:&body=\(urlSafeBody)") {
    WKExtension.sharedExtension().openSystemURL(url)
}


回答2:

Thanks to @Jatin for finding the openSystemURL(url: NSURL) function.

Here's the code:

let messageBody = "Hello World!"
let urlSafeBody = messageBody.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
WKExtension.sharedExtension().openSystemURL(NSURL(string: "sms:&body=\(urlSafeBody)")!)