正确使用调度组

时间:2018-01-24 05:49:25

标签: swift grand-central-dispatch

所以我知道调度组是一个高级GCD主题,允许您监视一组任务的完成情况。

它们通常通过将已启动的项目数与已完成的数字相匹配来工作。您可以通过分别在调度组实例上调用enter()和leave()来开始和完成新项目。当已启动的任务数等于已完成的数量时,调度组可以通知您所有任务都已执行。

    //will show the vents that a user is attending
    static func Events(for user: User, completion: @escaping ([Event]) -> Void)
    {
        var currentEvents = [Event]()

        //Getting firebase root directory
        let ref = Database.database().reference().child("users").child(user.uid).child("Attending")


        ref.observe(.value, with: { (snapshot) in
         //   print(snapshot)

//            guard snapshot.children.allObjects is [DataSnapshot] else {
//                return completion([])
//            }

            guard let eventDictionary = snapshot.value as? [String: Any] else {
                return completion([])
            }

          //  print(snapshot)
            let dispatchGroup = DispatchGroup()

            eventDictionary.forEach({ (key,value) in
             //   print(key)
             //   print(value)
                EventService.show(forEventKey: key , completion: { (event) in
                    dispatchGroup.enter()
                    AttendService.isEventAttended(event, byCurrentUserWithCompletion: { (isAttended) in
                        event?.isAttending = isAttended
                        dispatchGroup.leave()

                    })
                     currentEvents.append(.init(currentEventKey: key , dictionary: (event?.eventDictionary)!))
                })
            })

            dispatchGroup.notify(queue: .main, execute: {
                completion(currentEvents)
            })
        })
    }

我尝试在当前方法中使用一些调度组来完成此任务,但是在完成时似乎没有返回任何内容。任何人都可以帮我安排dispath组方法吗?

0 个答案:

没有答案