问题
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)")!)
来源:https://stackoverflow.com/questions/34361531/how-can-i-programmatically-compose-a-message