message
系统信息编写器发送短信或 iMessage。
系统短信 / iMessage 撰写:弹出 Messages 编辑器发送文本或附件。
边界:仅唤起系统信息界面,用户确认后才发送;不能静默群发短信。模拟器上可能不可用。
#模块概览
| 项 | 说明 |
|---|---|
| 导入 | import message |
| 适合做什么 | 快速发短信、分享链接、附带文件 |
| 调用时机 | compose() 放在按钮回调 |
| 推荐顺序 | can_send() → compose(recipients, body, ...) |
| 返回值 | sent / cancelled / failed |
#快速开始
已复制
import message
if not message.can_send():
print("此设备无法发送短信")
else:
result = message.compose(
["+8613800138000"],
"Hello from PythonIDE",
)
print(result)
#AppUI 示例
已复制
import appui
import message
state = appui.State(
can_send="—",
phone="+8613800138000",
body="来自 PythonIDE 的测试短信",
result="尚未发送",
)
def refresh_can_send():
state.can_send = "是" if message.can_send() else "否"
def send_sms():
refresh_can_send()
if state.can_send != "是":
state.result = "无法发送短信"
return
result = message.compose([state.phone], state.body)
state.result = result
def body():
return appui.NavigationStack(
appui.Form([
appui.Section("短信", [
appui.TextField("号码", text=state.phone),
appui.TextEditor(text=state.body).frame(min_height=80),
appui.Button("撰写短信", action=send_sms)
.button_style("bordered_prominent"),
]),
appui.Section("状态", [
appui.LabeledContent("可发送", value=state.can_send),
appui.LabeledContent("结果", value=state.result),
]),
]).navigation_title("短信")
)
appui.run(body, state=state)
#API 参考
#速查
| API | 作用 |
|---|---|
can_send() | 设备能否发短信 → bool |
compose(recipients, body='', attachments=None) | 弹出编辑器 → 结果字符串 |
MessageError | 原生能力入口失败异常 |
#compose
compose(recipients, body='', attachments=None)
| 参数 | 说明 |
|---|---|
recipients | 手机号或 Apple ID,字符串或列表 |
body | 正文 |
attachments | 文件路径列表 |
已复制
result = message.compose(["+8613800138000"], "你好")
# sent | cancelled | failed
#常见错误
| 错误写法 | 后果 | 修正 |
|---|---|---|
未检查 can_send() | 编辑器打不开 | 先判断可用性 |
在 body() 里 compose | 每次刷新弹窗 | 放进按钮回调 |
| 期望批量静默发送 | 系统不允许 | 需用户逐条确认 |
| 模拟器测试 | 常返回不可用 | 在真机验证 |
#相关文档
#预期效果
运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。