微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

嵌套调度组Swift

用户在我的应用程序中创建新组时,我必须将邀请推送到数据库以及其他信息.我已经开始使用dispatch Groups来跟踪成功发送所有信息的时间,因此我可以解除该视图.

我正在尝试为邀请使用调度组,为所有数据使用另一个调度组.这就是我所拥有的:

// Push new data to db
func createGroup(onSccess completion:@escaping () -> Void) {
    let invitedispatchGroup = dispatchGroup()
    let datadispatchGroup = dispatchGroup()

    let uid = FIRAuth.auth()?.currentUser?.uid
    let name = String(uid!) + "_" + nameTextField.text!

    // push invites
    datadispatchGroup.enter()
    for invite in invites {
        invitedispatchGroup.enter()
        let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites")
        ref.updateChildValues([name: nameTextField.text!]) { (error,ref) -> Void in
            invitedispatchGroup.leave()
        }
    }
    invitedispatchGroup.notify(queue: dispatchQueue.main,execute: {
        datadispatchGroup.leave()
    })

    // store picture
    datadispatchGroup.enter()
    let storageRef = Firstorage.storage().reference().child("profile_images").child("\(name).png")
    if let uploadData = UIImagePNGRepresentation(profImage.resizeImage(targetSize: CGSize(width: 500,height: Int(500*(profImage.size.height/profImage.size.width))))) {
        storageRef.put(uploadData,Metadata: nil,completion: { (Metadata,error) in
            datadispatchGroup.leave()
        })
    }

    // store pet info
    datadispatchGroup.enter()
    let petRef = FIRDatabase.database().reference().child("pets").child(name)
    petRef.setValue(["mod":uid!,"name":nameTextField.text!,"members":[uid!]]) { (error,ref) -> Void in
        datadispatchGroup.leave()
    }

    // store user info
    datadispatchGroup.enter()
    let userRef = FIRDatabase.database().reference().child("users").child(uid!).child("pets")
    userRef.updateChildValues([name: true]) { (error,ref) -> Void in
        datadispatchGroup.leave()
    }

    datadispatchGroup.notify(queue: dispatchQueue.main,execute: {
        completion()
    })
}

如您所见,当invitesDipatchGroup完成时,它将保留相应的datadispatchGroup.

我是dispatch小组的新手,想听听这是否是采取这种任务的正确方法.

这是异步任务跟踪的一种非常好的方法.

检查所有代码路径是否都包含leave()非常重要.你有一个潜在的错误,如果if let没有值不是可选的.修正了这里:

func createGroup(onSccess completion:@escaping () -> Void) {
    [...]
    // store picture
    datadispatchGroup.enter()
    let storageRef = Firstorage.storage().reference().child("profile_images").child("\(name).png")
    if let uploadData = UIImagePNGRepresentation(profImage.resizeImage(targetSize: CGSize(width: 500,error) in
            datadispatchGroup.leave()
        })
    } else {
        datadispatchGroup.leave()
    }
    [...]
}

通常,还要确保在所使用的方法的所有代码路径中调用所有完成块. Firebase中可能存在一个错误,或者可能在这方法的文档中没有调用完成.但同样,这是要走的路.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐