iOS共享扩展中的Firebase runTransactionBlock()

时间:2015-11-27 04:45:57

标签: ios firebase ios-extensions

我的共享扩展程序在didSelectPost()细分中包含以下代码:

override func didSelectPost() {
    if self.sharedURL != nil {
            // Send data to Firebase
            self.myRootRef.runTransactionBlock({
                (currentData:FMutableData!) in
                var value = currentData.value as? String
                // Getting the current value
                // and checking whether it's null
                if value == nil {
                    value = ""
                }
                // Setting the new value to the clipboard
                // content
                currentData.value = self.sharedURL?.absoluteString

                // Finalizing the transaction
                return FTransactionResult.successWithValue(currentData)
                }, andCompletionBlock: {
                    // Completion Check
                    (error:NSError!, success:Bool, data:FDataSnapshot!) in
                    print("DEBUG- We're done:\(success) and \(error)")
                }
            )
        }

        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}

我在运行时遇到以下错误:

host connection <NSXPCConnection: 0x7fb84af2e8c0> connection from pid 16743 invalidated

我认为此错误是由andCompletionBlock引起的,与以下问题有关:Debug info when run today extension

如何干净利落地成功处理上述交易的完成状态?

1 个答案:

答案 0 :(得分:1)

就像您所说的答案一样,NSXPCConnection错误并不重要。

问题是.runTransactionBlock()是异步的,.completeRequestReturningItems()会被调用并退出扩展程序,然后才能从Firebase数据库中获取值。

尝试在.completeRequestReturningItems()中运行andCompletionBlock

override func didSelectPost() {
    if self.sharedURL != nil {
            // Send data to Firebase
            self.myRootRef.runTransactionBlock({
                (currentData:FMutableData!) in
                var value = currentData.value as? String
                // Getting the current value
                // and checking whether it's null
                if value == nil {
                    value = ""
                }
                // Setting the new value to the clipboard
                // content
                currentData.value = self.sharedURL?.absoluteString

                // Finalizing the transaction
                return FTransactionResult.successWithValue(currentData)
                }, andCompletionBlock: {
                    // Completion Check
                    (error:NSError!, success:Bool, data:FDataSnapshot!) in
                            self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
                }
            )
        }

}