调度队列异步呼叫

时间:2019-07-11 23:55:06

标签: swift core-data concurrency dispatch-async dispatch-queue

我正在另一个网络请求内的for循环内触发网络请求。我正在使用Core Data,但我可以肯定这不是Core Data问题,而是异步问题。

Firebase请求中的2条打印语句正确打印了数据,但是没有DispatchQueue时,数组返回为空(在网络请求完成之前)。

这是崩溃的照片: Crash

这是代码本身:

var userReps = [UserRepresentation]()

// Fetch all Friends -> update Core Data accordingly
func fetchFriendsFromServer(completion: @escaping (Error?) -> Void = { _ in}){
    let backgroundContext = CoreDataStack.shared.container.newBackgroundContext()

    // 1. Fetch all friends from Firebase
    FirebaseDatabase.UserDatabaseReference.child(CoreUserController.shared.userPhoneNumber).child(UserKeys.UserFriends).child(UserKeys.UserAcceptedFriends).observe(.value) { (data) in
        if let dictionary = data.value as? [String: String] {
            var userReps = [UserRepresentation]()
            let group = DispatchGroup()

            group.enter()
            for friend in dictionary {
                let friendName = friend.value
                let friendId = friend.key

                FirebaseDatabase.UserDatabaseReference.child(friendId).observe(.value, with: { (data) in
                    if let dictionary = data.value as? [String: Any] {
                        guard let gender = dictionary[UserKeys.UserGender] as? String else {return}
                        guard let bio = dictionary[UserKeys.UserBio] as? String else {return}
                        guard let status = dictionary[UserKeys.UserStatus] as? String else {return}
                        guard let avatarUrl = dictionary[UserKeys.UserAvatarUrlKey] as? String else {return}

                        let friendRepresentation = UserRepresentation(avatarUrl: avatarUrl, name: friendName, number: friendId, gender: gender, status: status, bio: bio)
                        userReps.append(friendRepresentation)
                        print("HERE, friends fetched: ", friendRepresentation)
                        print("HERE, reps fetched: ", userReps)
                        group.leave()
                    }
                })
            }

            group.notify(queue: .main) {
                // 2. Update Core Data value with Firebase values
                self.updateFriends(with: userReps, in: backgroundContext)

                // 3. Save Core Data background context
                do {
                    try  CoreDataStack.shared.save(context: backgroundContext)
                } catch let error {
                    print("HERE. Error saving changes to core data: \(error.localizedDescription)")
                }
            }
        }
    }
}

任何帮助都会大有帮助

1 个答案:

答案 0 :(得分:1)

因为

let group = DispatchGroup()

是局部变量,您可以在此处使用观察

FirebaseDatabase.UserDatabaseReference.child(friendId).observe(.value, with: { (data) in

在函数释放后,将其重新设置为实例变量或进行单个观察

 FirebaseDatabase.UserDatabaseReference.child(friendId).observeSingleEvent(of:.value) { (data) in

还要在for循环内输入

for friend in dictionary {  
  group.enter()