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)")!)