Firebase查询和完成

时间:2016-08-22 13:19:28

标签: ios swift firebase firebase-realtime-database

我在编写流程时遇到一些麻烦,允许用户删除其Firebase帐户,该帐户会删除他们的帐户以及他们帐户中包含图片的所有帖子。我正在查询Firebase数据库中的用户帖子,在它们出来时循环并删除它们。在此循环的中间,我调用传递图像URL的函数从Firebase存储中删除图像。我遇到的问题是由于异步的原因我无法获得有序的结果。我认为有完成处理程序会给它一些订单。我应该调查调度组吗?非常感谢任何帮助。

使用函数调用开始我的进程:

         ref.deleteFirebaseDBUsersPosts(deleter) { (success) -> Void in 
            if success {
                print("The user and their info is completely gone!")
            }

        }

查询Firebase并通过用户帖子和删除循环的功能:

func deleteFirebaseDBUsersPosts(uid: String, completion:(success: Bool) -> Void) {
  let usersCurrentId = uid

    ref.child(“posts”).queryOrderedByChild("uid").queryEqualToValue("\(uid)").observeEventType(.Value, withBlock: {snapshot in

        if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {

            for snap in snapshot{

                print("SNAP: \(snap)")
                if let postedImg = snap.childSnapshotForPath("imageUrl").value {
                    let postImgUrl = postedImg as! String
                       self.deletingOldUsersImgsFromStorage(postImgUrl) { (success) -> Void in   
                    }
                }
                 let key = snap.key
                 ref.child(“posts”).child(key).removeValue()
                 ref.child(“users”).child(usersCurrentId).removeValue()
             }
              print("COMPLETING")
              completion(success: true)
        }

    })
}

从Firebase存储中删除图像:

 func deletingOldUsersImgsFromStorage(postImgUrl: String!, completion:(success: Bool) -> Void) {
    let deleteImgRef = ref.child(“images”).child("[imageNAME]")
    deleteImgRef.deleteWithCompletion({ (error) in
        if (error != nil) {
            print("DEVELOPER: There was an error when trying to delete the image from Firebase Storage")
        } else {
            print("IMAGE SUCCESSFULLY DELETED FROM FIREBASE STORAGE")
        }
        completion(success: true)
    })
}

1 个答案:

答案 0 :(得分:2)

从Firebase删除用户及其数据时,我遇到了类似的问题。在我删除数据的方法完成后,我使用调度组处理它以删除用户。

func deleteUsersData(completion: (success: Bool) -> Void) {}

func deleteUsersPhotoUrl(completion: (success: Bool) -> Void) {}

func deleteUserFromFirebase(completion: (success: Bool) -> Void) {}

let group = dispatch_group_create()

dispatch_group_enter(group)
deleteUsersData { (success) in
    if success {
        dispatch_group_leave(group)
    }
}

dispatch_group_enter(group)
deleteUsersPhotoUrl { (success) in
    if success {
        dispatch_group_leave(group)
    }
}

dispatch_group_notify(group, dispatch_get_main_queue()) {
    deleteUserFromFirebase({ (success) in
        print("Completely deleted user from Firebase")
    })
}

调度组非常适合处理此类情况,您只希望在指定的其他任务完成后执行任务。以下是有关如何使用dispatch groups的更多信息。