Mac开发App执行AppleScript

沙盒里面运行AppleScript可不是那么简单,如下

项目的.entitlements文件记得要搞成这样,弄完了别忘了clean your project folder然后再测试

image.png
com.apple.security.automation.apple-events
    
    com.apple.security.temporary-exception.apple-events
    
        com.apple.systemevents
    

plist文件


image.png
    NSAppleEventsUsageDescription
    

把文件写入到

var dir = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]

这里面

写入的代码:

func check() -> Bool {
    let path = NSSearchPathForDirectoriesInDomains(.applicationScriptsDirectory, .userDomainMask, true)[0]
    let file = "\(path)/你写好的脚本编辑器的内容.scpt"
    return FileManager.default.fileExists(atPath: file)
}

func install() {

    if !check() {

        let panel = NSSavePanel()
        panel.title = "保存AppleScript"
        panel.message = "请保存AppleScript文件至Application Scripts目录才可使用"
        //        panel.allowedFileTypes = ["json"]
        panel.nameFieldStringValue = "你写好的脚本编辑器的内容.scpt"
        panel.directoryURL = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]
        panel.canCreateDirectories = false
        panel.delegate = self

        if panel.runModal() == .OK {
            if let url = panel.url {
                //  这里是你的项目的脚本的resource文件
                if let resourceUrl = Bundle.main.url(forResource: "你写好的脚本编辑器的内容", withExtension: "scpt") {
                    do {
                        let data = try Data(contentsOf: resourceUrl)
                        try data.write(to: url)
                        return

                    } catch {
                        panel.cancel(nil)
                        install()
                    }
                }
            }
        }
        panel.cancel(nil)
        install()
    }
}

运行脚本的代码:

var dict:NSDictionary?
        
var dir = FileManager.default.urls(for: .applicationScriptsDirectory, in: .userDomainMask)[0]
dir.appendPathComponent("你写好的脚本编辑器的内容.scpt")
        
let script = NSAppleScript(contentsOf: dir, error: &dict)
script?.executeAndReturnError(&dict)
        
print(dict)

帮助链接:

重要链接(必看):

https://stackoverflow.com/questions/21924932/how-to-run-an-applescript-from-a-sandboxed-application-on-a-mac-os-x/21939202

https://www.jessesquires.com/blog/2018/11/17/executing-applescript-in-mac-app-on-macos-mojave/

国产:
https://www.foolishtalk.org/2019/11/10/%E5%9C%A8Mac-app%E4%B8%8A%E6%89%A7%E8%A1%8CAppleScript/

其他:
https://stackoom.com/question/3nfRM/%E5%9C%A8Xamarin%E4%B8%AD%E4%BD%BF%E7%94%A8NSAppleEventsUsageDescription%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E9%A1%B9

https://joshspicer.com/applescript

你可能感兴趣的:(Mac开发App执行AppleScript)