Mac 使用Objective-C和AppleScript脚本交互

本文介绍了如何在Mac上通过Xcode创建一个AppleScript应用,以Objective-C为桥梁与AppleScript进行交互。在实现过程中,由于权限问题会遇到错误,解决方法是在info.plist中添加相应描述并请求用户授权。通过示例代码,展示了如何控制Safari打开网页,以及如何避免从头开始创建工程。
摘要由CSDN通过智能技术生成

新建Xcode工程,选择macOS平台,选择Other类型中的AppleScript App。
在工程中找到appleScript后缀文件,在applicationWillFinishLaunching_方法中添加测试代码,此处以Safari为例。

on applicationWillFinishLaunching_(aNotification)
	-- Insert code here to initialize your application before any files are opened
    	--Safari打开网页
        tell application "Safari"
            activate
            --新建tab页,传入URL
            tell front window
                --get every tab
                --get URL of tab 1
                make new tab with properties {
   URL:"https://www.apple.com.cn"}
            end tell
        end tell
end applicationWillFinishLaunching_

编译运行后回在控制台报错:*** -[AppDelegate applicationWillFinishLaunching:]: Not authorized to send Apple events to Safari. (error -1743)
是因为App还没有获取到发送AppleScript事件的用户权限,所以不能直接控制Safari打开网页,在Xcode工程中的info.plist中添加Privacy - AppleEvents Sending Usage Description,后面添加上描述,再次启动就会弹出授权弹框。
info.plist添加AppleEvents授权描述
授权确认弹框

最终AppDelegate.applescript文件完整示例代码

script AppDelegate
	property parent : class "NSObject"
	
    -- 载入OC类
    property Test : class "Test"
    
	-- IBOutlets
	property theWindow : missing value
	
	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
        
        --Safari打开网页
        tell application "Safari"
            activate
            --新建tab页,传入URL
            tell front window
                --get every tab
                --get URL of tab 1
                make new tab with properties {
   URL:"https://www.apple.com.cn"}
            end tell
        end tell
       
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值