How can I programmatically compose a message?

最后都变了- 提交于 2019-12-10 13:38:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!