Firebase Firestore无法在Swift Share Extension中工作

时间:2019-07-01 07:13:55

标签: swift firebase google-cloud-firestore share-extension

我正在Swift中构建一个Share Extension,它将文档保存到Firestore。到目前为止,我已经能够通过钥匙串共享和应用程序组对正确的用户进行身份验证。我还可以从新文档参考中获取documentID:

var ref = Firestore.firestore().collection("stuff").document()
print(ref.documentID) //prints the id

但是,当我尝试将某些内容保存到Firestore时,控制台中不会打印任何内容,这意味着我既不会从Firebase获得失败或成功的回调(请参阅下面的批处理更新)。这是我的ShareController.swift文件:

class ShareViewController: SLComposeServiceViewController {

  var sharedIdentifier = "asdf"

    override func viewDidLoad() {
      FirebaseApp.configure()
      setupKeychainSharing()
    }

    func setupKeychainSharing() {

      do {
        try Auth.auth().useUserAccessGroup(sharedIdentifier)
      } catch let error as NSError {

      }
    }

    override func isContentValid() -> Bool {
      return true
    }

    override func didSelectPost() {

      if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
        if let contents = content.attachments {
          for attachment in contents {

            if attachment.hasItemConformingToTypeIdentifier(m4aType) {

              attachment.loadItem(forTypeIdentifier: m4aType, options: nil, completionHandler:  { (results, error) in
                if error == nil {
                  if let url = results as? URL {

                    if let audioData = NSData(contentsOf: url) {
                      let fileName = url.lastPathComponent
                      if Auth.auth().currentUser != nil {

                        guard let myId = Auth.auth().currentUser?.uid else { return }

                         let batch = Firestore.firestore().batch()

                         let ref = Firestore.firestore().collection("projects").document()

                         let project: [String: Any] = [
                           "ownerId": myId,
                           "type" : "audio",
                           "extensionUrl" : audioUrl.absoluteString
                         ]

                         batch.updateData(project, forDocument: ref)

                         let privateRef = Firestore.firestore().collection("user-private").document(myId)
                         let privateUpdate: [String: Any] = [
                           "projects" : FieldValue.arrayUnion([ref.documentID])
                          ]
                          batch.updateData(privateUpdate, forDocument: privateRef)
                          batch.commit(completion: { (error) in
                            if let error = error {
                              print("error updating database: \(error.localizedDescription)")
                            } else {
                              print("Database updated successfully!!!!!")
                              self.extensionContext!.completeRequest( returningItems: [], completionHandler: nil)
                            }
                          })
                        }
                      }
                    }
                  }
                })
              }
            }
          }
       } 
    }
}

2 个答案:

答案 0 :(得分:0)

您似乎正在尝试在项目节点中创建其他文档并更新用户专用节点。如果是这样,问题中的代码将无法工作。

  

UpdateData:更新文档引用的文档中的字段。如果   文档不存在,写入批处理将失败。

这是一个工作批处理写入功能,该功能将文档添加到具有Firestore生成的文档ID和扩展名,ownerId和类型的子字段以及带有documentId为id_0的文档的user_private集合的项目节点。

func batchWrite() {
    let batch = self.db.batch()

    let ref = self.db.collection("projects").document()
    let project: [String: Any] = [
        "ownerId": "id_0",
        "type" : "audio",
        "extensionUrl" : "some url"
    ]
    batch.setData(project, forDocument: ref)

    let privateRef = self.db.collection("user-private").document("id_0")
    let privateUpdate: [String: Any] = [
        "projects" : "some projects"
    ]
    batch.setData(privateUpdate, forDocument: privateRef)

    batch.commit(completion: { (error) in
        if let error = error {
            print("error updating database: \(error.localizedDescription)")
        } else {
            print("Database updated successfully!!!!!")
        }
    })
}

请注意,self.db是对Firestore的类var引用。这样一来,您就不必继续键入Firestore.firestore()并改用self.db

还请注意,在这种情况下可能不需要批处理,因为它似乎不会同时发生大量写入。

如果您不使用批处理,则.addDocument会将文档添加到集合中。

这是一个将任务写入任务集合并自动生成documentId的函数

func writeTask() {
    let collectionRef = self.db.collection("tasks")
    let data = [
        "task": "some task"]
    var ref: DocumentReference? = nil
    ref = collectionRef.addDocument(data: data, completion: { err in
        if let error = err {
            print(error.localizedDescription)
        }

        print(ref?.documentID)
    })
}

答案 1 :(得分:0)

很可能没有为您的共享扩展名配置Firebase。打印语句不适用于共享扩展名。相反,您应该使用NSLog语句,即NSLog("refDocId:\(ref.DocumentId)")。然后在xcode中,导航到“窗口”>“设备和模拟器”>“打开控制台”。要在您的共享扩展程序中配置Firebase,请使用FirebaseApp.configure()