【问题标题】:Firebase Tasks in Swift / iOSSwift / iOS 中的 Firebase 任务
【发布时间】:2020-02-17 12:04:38
【问题描述】:

我是一名 android 开发人员,正在学习使用 swift 为 iOS 编写我的应用程序。我不确定如何运行多个 firebase(firestore 和实时数据库)异步编写任务并返回完成处理程序。在 android 中,我使用 Tasks API 并将其编写如下:

Task<Void> firestoreTask = firestoreDB.getDocument("users/someId").update("name", "some name");

Task<Void> realtimeTask = realtimeDB.child("users/someId/name/").setValue("some name");

Tasks.whenAll(firestoreTask, realtimeTask).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // if both tasks are successful
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if at least one of the two task fails
            }
        });

我似乎不知道如何快速编写这样的任务。有人可以指出我正确的方向吗?谢谢。

【问题讨论】:

标签: ios swift firebase firebase-realtime-database google-cloud-firestore


【解决方案1】:

以下代码将帮助您解决此问题

import Foundation

// Create a dispatch group object and add a didset observer to catch error in operation

var dispatchGroup:DispatchGroup? = DispatchGroup(){
    didSet{
        if dispatchGroup == nil{
            // here you can do whetever after at least one of the two task fails
            print("error in FirestoreTask or realtimeTask")
        }
    }
}

// do your firestoreTask in this method
func dofirestoreTask (){
    // Implement your firestore task here //

    let taskResponse = true // Remove this variable with your firestore task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

func dorealtimeTask(){
    // Implement your realTimeTask here task here //
    let taskResponse = true // Remove this variable with your realTime task response status
    if taskResponse == true{
        dispatchGroup?.leave()
    }else{
        dispatchGroup = nil
    }
}

dispatchGroup?.enter()
dofirestoreTask()
dispatchGroup?.enter()
dorealtimeTask()

dispatchGroup?.notify(queue: .main) {
    // here you can do whetever after both tasks are successful
    print("Both Success")
}

【讨论】:

    【解决方案2】:

    我认为在 iOS 中你只有闭包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      相关资源
      最近更新 更多