Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 确保在异步函数之后执行代码块_Swift_Asynchronous - Fatal编程技术网

Swift 确保在异步函数之后执行代码块

Swift 确保在异步函数之后执行代码块,swift,asynchronous,Swift,Asynchronous,我正在使用Firestore创建一个应用程序,我有一个功能,可以将一个用户添加到另一个用户的好友列表中,如果成功,则返回true。 这就是功能: static func addFriendToList(_ id: String) -> Bool { var friend: Friend! var isSuccessfullyAddedFriend: Bool = false let group = DispatchGroup() DispatchQueu

我正在使用Firestore创建一个应用程序,我有一个功能,可以将一个用户添加到另一个用户的好友列表中,如果成功,则返回true。 这就是功能:

static func addFriendToList(_ id: String) -> Bool {

    var friend: Friend!
    var isSuccessfullyAddedFriend: Bool = false
    let group = DispatchGroup()

    DispatchQueue.global(qos: .userInitiated).async {
        group.enter()
        // Getting user's deatils and creating a Friend object.
        FirestoreService.shared.getUserDetailsById(user: id) { (newFriend) in
            if newFriend != nil {
                friend = newFriend!
            }
            group.leave()
        }
        group.wait()

        group.enter()
        // Adding the new Friend Object to the friends list of the current user
        FirestoreService.shared.addUserToFriendsList(friend: friend) { (friendAdded) in
            if friendAdded {
                isSuccessfullyAddedFriend = true
                FirestoreService.shared.fetchFriendList()
            }
        }
        group.leave()
    }

    group.wait()
    return isSuccessfullyAddedFriend
}
我的问题是
addUserToFriendsList
是一个异步函数,并且
返回
isSuccessfullyAddedFriend
在变为
true
之前执行。 如您所见,我尝试使用DispatchGroup来克服这个问题,但没有成功,问题仍然存在。有没有其他更好的方法来实现这一点? 我需要
return
行发生在您需要的
addUserToFriendsList
之后

static func addFriendToList(_ id: String,completion:@escaping(Bool)->()) { 

        FirestoreService.shared.getUserDetailsById(user: id) { (newFriend) in

            FirestoreService.shared.addUserToFriendsList(friend: newFriend) { (friendAdded) in
                if friendAdded { 
                     FirestoreService.shared.fetchFriendList()
                     completion(true)
                }
                else {
                     completion(false)
                }

            }
        } 

}

召唤

Api.addFriendToList(){中的标志
打印(标志)
}

2注

1-Firebase调用在后台线程中运行,因此不需要全局队列


2-DispatchGroup用于多个并行任务,而不是串行任务

谢谢,我会试试这个。不过这仍然很有趣,有没有一种方法可以在异步完成后才执行一行呢?谢谢你的注释。我不知道Firebase的电话,很高兴知道。关于DispatchGroup,我也不知道,我一定会更多地了解它和它的用途。非常感谢。
Api.addFriendToList(<#id#>) { flag in
  print(flag)
}