iOS 操作扩展示例代码不工作

Oak*_*Oak 1 ios ios-app-extension

iOS Action Extension 示例代码似乎不起作用。

  1. 在 xCode 中,我创建一个新的 Swift 项目并选择 Single View Application。

  2. 然后我选择“文件”>“新建”>“目标”,然后选择“操作扩展”。我输入名称,选择 Swift,然后选择操作类型:无用户界面

  3. 然后我通过运行项目并选择 Safari 来测试扩展。我导航到 Google 网站。

  4. 我通过 Safari 中的“操作”图标启用该扩展。然后我按扩展图标在 Safari 中运行它,但没有任何反应。

  5. 我希望网页背景颜色发生变化,因为应该运行的 Action.js 代码设置背景颜色: document.body.style.background= "blue"

就好像 Action.js 代码永远不会被调用。 所有代码均来自默认的 Action Extension 模板,并且未进行任何修改。

信息表

<key>NSExtension</key>
    <dict>
        <key>NSExtensionAttributes</key>
        <dict>
            <key>NSExtensionActivationRule</key>
            <dict>
                <key>NSExtensionActivationSupportsFileWithMaxCount</key>
                <integer>0</integer>
                <key>NSExtensionActivationSupportsImageWithMaxCount</key>
                <integer>0</integer>
                <key>NSExtensionActivationSupportsMovieWithMaxCount</key>
                <integer>0</integer>
                <key>NSExtensionActivationSupportsText</key>
                <false/>
                <key>NSExtensionActivationSupportsWebPageWithMaxCount</key>
                <integer>1</integer>
            </dict>
            <key>NSExtensionJavaScriptPreprocessingFile</key>
            <string>Action</string>
        </dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.services</string>
        <key>NSExtensionPrincipalClass</key>
        <string>$(PRODUCT_MODULE_NAME).ActionRequestHandler</string>
    </dict>
Run Code Online (Sandbox Code Playgroud)

Tom*_*ton 5

此类扩展的 Xcode 项目模板的 Swift 版本中存在一个错误,显然是因为有人从 Objective-C 转换为 Swift 时出现错误。

长话短说:“found = true”这一行放错了地方。这会导致该方法doneWithResults在只应调用一次的情况下被调用两次。第一次调用就设置了self.extensionContext = nil。在第二次调用时,它尝试使用self.extensionContext并由于展开 nil 可选而引发异常。但异常消息被扩展系统吞掉了,所以没有任何线索。

如果您在项目模板中更改此代码:

itemProvider.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (item, error) in
    let dictionary = item as! [String: AnyObject]
    NSOperationQueue.mainQueue().addOperationWithBlock {
        self.itemLoadCompletedWithPreprocessingResults(dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! [NSObject: AnyObject])
    }
    found = true
})
Run Code Online (Sandbox Code Playgroud)

看起来像这样

itemProvider.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (item, error) in
    let dictionary = item as! [String: AnyObject]
    NSOperationQueue.mainQueue().addOperationWithBlock {
        self.itemLoadCompletedWithPreprocessingResults(dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! [NSObject: AnyObject])
    }
})
found = true
Run Code Online (Sandbox Code Playgroud)

...然后它按预期工作。

我提交了有关此问题的错误rdar://22482042,我鼓励您也提交一个。