AppleScript中display notification快速循环显示异常问题求助
解决macOS 10.13中AppleScript循环通知被合并的问题
我太懂这种 frustration 了——在macOS 10.13里,快速循环调用display notification时系统自动合并成“N new notifications”的提示,完全没法传递脚本的具体进度信息,尤其是处理本地磁盘这种时长不确定的任务时,之前的间隔触发法根本不顶用。下面给你两个靠谱的通用解决方案:
方案1:用AppleScriptObjC发送带唯一标识的通知(推荐)
通过直接调用NSUserNotification框架,我们可以给每个通知设置唯一标识符,让系统无法合并它们。这个方法不受循环时长限制,适用于所有场景。
use framework "Foundation" use scripting additions -- 封装发送唯一通知的函数 on sendUniqueNotification(notificationTitle, notificationSubtitle, notificationText) -- 创建通知对象 set newNotification to current application's NSUserNotification's alloc()'s init() -- 设置通知内容 newNotification's setTitle:notificationTitle newNotification's setSubtitle:notificationSubtitle newNotification's setInformativeText:notificationText -- 设置唯一标识符(用时间戳确保每个通知都不一样) set timestamp to current application's NSDate's date()'s timeIntervalSince1970() as string newNotification's setIdentifier:timestamp -- 发送通知 current application's NSUserNotificationCenter's defaultUserNotificationCenter()'s deliverNotification:newNotification end sendUniqueNotification -- 示例:循环中调用 repeat with taskNumber from 1 to 10 sendUniqueNotification("任务进度", "第" & taskNumber & "项", "正在处理本地文件...") delay 0.3 -- 模拟快速循环的任务处理间隔 end repeat
为什么这招管用?
macOS的通知中心只会合并标识符相同的通知,我们给每个通知分配基于时间戳的唯一ID,系统就会把它们当成独立通知逐一显示,再也不会出现汇总提示。
方案2:给每个通知添加动态差异内容
如果不想引入AppleScriptObjC,最简单的办法就是让每个通知的内容存在细微差异——系统只会合并完全相同的通知。你可以在通知的标题、副标题或正文里加入循环计数器、当前时间这类动态内容:
repeat with taskNumber from 1 to 10 set currentTime to (current date) as string display notification "正在处理第" & taskNumber & "项任务" with title "脚本运行中" subtitle "更新于: " & currentTime delay 0.3 end repeat
优缺点
- 优点:代码简单,不需要额外框架依赖
- 缺点:通知内容会多出动态信息(比如时间),如果追求简洁的话可能不太理想
总结
如果需要完全控制通知显示、不希望内容有冗余,优先用方案1;如果只是临时解决问题、追求快速实现,方案2足够应付大部分场景。这两个方法都不需要提前知道循环时长,完美适配本地磁盘处理这类进度不可预知的场景。
内容的提问来源于stack exchange,提问作者Jeff Porten
相关产品推荐
相关产品推荐

