iOS Action Extension Sample Code Not Working

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 05:30:48

There's a bug in the Swift version of Xcode's project template for this kind of extension, apparently because of an error when someone was converting from Objective-C to Swift.

To make a long story short: the line that reads "found = true" is in the wrong place. This causes the method doneWithResults to be called twice when it should only be called once. On the first call it sets self.extensionContext = nil. On the second call it tries to use self.extensionContext and throws an exception due to unwrapping a nil optional. But the exception message gets swallowed by the extension system, so there are no clues.

If you change this code in the project template:

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

to look like this:

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

...then it works as expected.

I filed the bug rdar://22482042 about this and I encourage you to file one as well.

I found a solution: create the project and app extension in Objective C, instead of Swift, and everything works fine. So apparently there is a bug in the Swift implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!