如何通过NSAppleScript在Mail.app运行AppleScript并解析结果为字符串数组
获取Mail.app账户列表的Swift解决方案
问题分析
你遇到的scriptResult.coerce(toDescriptorType: typeAEList)返回nil的问题,核心原因是:
- 原AppleScript返回的是字典组成的AE列表,而
scriptResult本身已经是AEList类型,无需额外强制转换; - 列表中的元素是AERecord(AppleScript字典),不能直接提取字符串,需要先解析字典内的字段。
最简解决方案(仅获取账户名)
如果只需要账户名称数组,直接修改AppleScript返回纯账户名列表,Swift端解析会更简单:
修改后的AppleScript
tell application "Mail" -- 直接返回所有账户的名称列表 return name of every account end tell
对应Swift代码
import Foundation struct EmailAccounts { func getAccountNames() -> [String] { let appleScriptSource = """ tell application "Mail" return name of every account end tell """ var error: NSDictionary? var accountNames: [String] = [] if let scriptObject = NSAppleScript(source: appleScriptSource) { let scriptResult = scriptObject.executeAndReturnError(&error) // 直接获取返回的AE列表 if let listDescriptor = scriptResult.listDescriptor { for index in 1...listDescriptor.numberOfItems { if let accountName = listDescriptor.atIndex(index)?.stringValue { accountNames.append(accountName) } } } else { // 打印错误便于排查 if let errorDetails = error { print("AppleScript执行错误: \(errorDetails)") } } } return accountNames } }
保留原结构的解决方案(后续可扩展处理邮箱)
如果需要保留原AppleScript的返回结构(方便后续处理多邮箱),则需要解析列表中的每个字典元素:
Swift代码修改版
import Foundation struct EmailAccounts { func getAccountNames() -> [String] { let appleScriptSource = """ tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell """ var error: NSDictionary? var accountNames: [String] = [] if let scriptObject = NSAppleScript(source: appleScriptSource) { let scriptResult = scriptObject.executeAndReturnError(&error) if let listDescriptor = scriptResult.listDescriptor { for index in 1...listDescriptor.numberOfItems { // 将列表项强制转换为AppleScript字典(AERecord) guard let dictDescriptor = listDescriptor.atIndex(index)?.coerce(toDescriptorType: typeAERecord) else { continue } // 提取字典中对应账户名的字段 guard let nameDescriptor = dictDescriptor.descriptor(forKey: "accName") else { continue } if let accountName = nameDescriptor.stringValue { accountNames.append(accountName) } } } else { if let errorDetails = error { print("AppleScript执行错误: \(errorDetails)") } } } return accountNames } }
关键说明
- 不要对已为
AEList类型的scriptResult调用coerce(toDescriptorType: typeAEList),直接使用scriptResult.listDescriptor获取列表即可; - AppleScript返回的字典在Swift中对应
AERecord类型,需要通过键名提取对应字段; - 优先选择最简方案,减少不必要的复杂解析逻辑。
内容的提问来源于stack exchange,提问作者Konrad
相关产品推荐
相关产品推荐

