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

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

  1. 在xCode中,我创build了一个新的Swift项目并selectSingle View Application。

  2. 然后selectFile> New> Target,然后selectAction Extension。 我input一个名字,selectSwift,然后selectAction Type:No User Interface

  3. 然后通过运行项目并selectSafari来testing扩展。 我导航到Google网站。

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

  5. 我期望网页的背景颜色可以改变,因为应该运行的Action.js代码设置了背景颜色:document.body.style.background =“blue”

就好像Action.js代码永远不会被调用。 所有的代码都来自默认的Action Extension模板,并没有被修改。

的Info.plist

<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> 

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

长话短说:读取“find=真”的行是在错误的地方。 这会导致方法doneWithResults被调用两次,只应调用一次。 在第一次调用它设置self.extensionContext = nil 。 在第二次调用时,它尝试使用self.extensionContext并由于展开一个nil可选项而引发exception。 但是exception消息被扩展系统吞噬了,所以没有线索。

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

 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 }) 

看起来像这样

 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 

…然后它按预期工作。

我提交了关于这个bug的rdar://22482042 ,我也鼓励你提交一个。

我find了一个解决scheme:在Objective C中创build项目和应用程序扩展,而不是Swift,一切工作正常。 所以显然在Swift实现中有一个错误。