Swift 使用Chrome脚本桥强制展开错误
我正在尝试苹果的脚本桥与谷歌浏览器交互。我从中的代码开始 我使用Swift 使用Chrome脚本桥强制展开错误,swift,applescript,applescript-objc,Swift,Applescript,Applescript Objc,我正在尝试苹果的脚本桥与谷歌浏览器交互。我从中的代码开始 我使用sdef和sdp命令创建了.h文件 我已经包括了这个文件,还创建了桥接头,并在桥接头中导入了chrome的头文件。但问题在于在Swift中使用标题。代码很旧,Swift已经改变了很多 我的Swift文件: import Cocoa import ScriptingBridge var chromeObject = SBApplication.init(bundleIdentifier: "com.google.Chrome")!
sdef
和sdp
命令创建了.h
文件
我已经包括了这个文件,还创建了桥接头,并在桥接头中导入了chrome的头文件。但问题在于在Swift中使用标题。代码很旧,Swift已经改变了很多
我的Swift文件:
import Cocoa
import ScriptingBridge
var chromeObject = SBApplication.init(bundleIdentifier: "com.google.Chrome")! as AnyObject
print(chromeObject.closeable)
我在说一个错误
致命错误:在展开可选值时意外发现nil
我做错了什么?来自以下文档: 返回值
SBApplication
子类的初始化共享实例,该子类表示绑定标识符为ident
的目标应用程序。如果找不到此类应用程序或该应用程序没有脚本接口,则返回nil
您应该检查init
方法在强制展开之前是否返回实例,如:
if let chromeObject = SBApplication.init(bundleIdentifier: "com.google.Chrome") as? AnyObject {
print(chromeObject.closeable)
}
SBApplication
返回应用程序对象。您可以在.h
文件中看到不同的界面
@interface ChromeApplication : SBApplication
@interface ChromeWindow : SBObject <ChromeGenericMethods>
@interface ChromeApplication (ChromiumSuite)
@interface ChromeTab : SBObject <ChromeGenericMethods>
@interface ChromeBookmarkFolder : SBObject <ChromeGenericMethods>
@interface ChromeBookmarkItem : SBObject <ChromeGenericMethods>
您应该检索-(SBElementArray*)窗口
使用closable
。同样,在windows中,您有选项卡数组等
例如,在AppleScript中获取每个选项卡的URL和标题:
tell application "Google Chrome"
set a to ""
repeat with w in windows
repeat with t in tab in w // Getting tab object from window
set a to a & linefeed & title of t & " -URL: " & URL of t
end repeat
end repeat
end tell
Swift中的等效值为:
import Cocoa
import ScriptingBridge
var chromeObject: AnyObject = SBApplication.init(bundleIdentifier: "com.google.Chrome")!
var f = chromeObject.windows() // get the windows from application
for i in f!
{
var t = (i as AnyObject).tabs() // get the tabs from windows
for j in t!
{
print(((j as AnyObject).title as String) + " -URL: " + ((j as AnyObject).url as String))
}
}
希望有帮助 是否安装了Chrome的可能副本?@JoshCaswellYes@JoshCaswell唯一有效的命令是chromeObject.activate()
@psh使用ScriptingBridge
的问题是文档的表达性不强。所以这就是为什么你没有得到。是否确实要继续使用ScriptingBridge
,而不是直接使用AppleScript
?一旦你了解了它的工作原理,这就很容易了,但是如果你使用iTunes.sdef,它有这么多接口,那就太麻烦了。实际上问题出在chromeObject.closeable
。它总是返回nil
。但是当我尝试使用Obj-c时,它可以正常工作,但有一些警告。当你打印时,你会得到那个错误吗?如果你有客观的C代码,为什么不发布呢?也许我们可以帮你把它翻译成Swift?谢谢你的帮助@你引用的苹果文档描述了AppleScript语言是如何工作的。AS定义了许多标准的内置数据类型(字符串、列表等),并通过脚本对象支持一种基于原型的OOP。而其Apple事件桥的工作方式则完全不同:应用程序自动化不是OOP,而是RPC加上简单的一级关系查询。(ASLG在解释这一点上比没用更糟糕;库克博士的要好得多。SB也对此大做文章,因此建议你尽量坚持。)
import Cocoa
import ScriptingBridge
var chromeObject: AnyObject = SBApplication.init(bundleIdentifier: "com.google.Chrome")!
var f = chromeObject.windows() // get the windows from application
for i in f!
{
var t = (i as AnyObject).tabs() // get the tabs from windows
for j in t!
{
print(((j as AnyObject).title as String) + " -URL: " + ((j as AnyObject).url as String))
}
}