Swift 完成时总是零分
我正在尝试获取Swift 完成时总是零分,swift,google-cloud-firestore,Swift,Google Cloud Firestore,我正在尝试获取Firestore中的地图数据,如下所示: 我试图获取数据,创建一个友元对象的数组,并在完成处理程序中返回数组 这就是我所拥有的: func fetchFriendList(_ id: String, completion: @escaping([Friend]?)->()) { var fetchedFriends: [Friend]? db.collection(USERS_COLLECTION).document(id).getDocument { (
Firestore中的地图数据
,如下所示:
我试图获取数据,创建一个友元对象的数组
,并在完成处理程序中返回数组
这就是我所拥有的:
func fetchFriendList(_ id: String, completion: @escaping([Friend]?)->()) {
var fetchedFriends: [Friend]?
db.collection(USERS_COLLECTION).document(id).getDocument { (doc, err) in
if err == nil && doc != nil {
guard let results = doc?.data()?[USER_FOLLOWING] as? [String: Any] else { return }
for result in results { // Getting the data in firebase
if let resultValue = result.value as? [String: Any] { // Getting only the value of the MAP data, we do not need the key.
//Getting the fields from the result
guard let id = resultValue[FRIEND_ID] as? String else { return }
guard let profilePic = resultValue[FRIEND_PROFILE_PIC] as? String else { return }
guard let username = resultValue[FRIEND_NAME] as? String else { return }
guard let email = resultValue[FRIEND_MAIL] as? String else { return }
//Creating a new Friend object from the fields
let friend = Friend(id: id, profilePicture: profilePic, username: username, email: email)
fetchedFriends?.append(friend)
}
completion(fetchedFriends)
}
}else {
print(err!.localizedDescription)
completion(nil)
}
}
}
我试着打印结果,结果值等等,它们不是零。
但是,在尝试附加和打印fetchedFriends数组之后,我得到了nil,并且完成也是nil。
我真的不明白为什么会发生这种情况。问题是您没有初始化变量fetchedFriends,并且在向其添加数据时使用了可选类型。由于它尚未初始化,它将跳过附加到它。您应该在开始时初始化它。更新后的代码如下
func fetchFriendList(_ id: String, completion: @escaping([Friend]?)->()) {
var fetchedFriends: [Friend] = []
db.collection(USERS_COLLECTION).document(id).getDocument { (doc, err) in
if err == nil && doc != nil {
guard let results = doc?.data()?[USER_FOLLOWING] as? [String: Any] else { return }
for result in results { // Getting the data in firebase
if let resultValue = result.value as? [String: Any] { // Getting only the value of the MAP data, we do not need the key.
//Getting the fields from the result
guard let id = resultValue[FRIEND_ID] as? String else { return }
guard let profilePic = resultValue[FRIEND_PROFILE_PIC] as? String else { return }
guard let username = resultValue[FRIEND_NAME] as? String else { return }
guard let email = resultValue[FRIEND_MAIL] as? String else { return }
//Creating a new Friend object from the fields
let friend = Friend(id: id, profilePicture: profilePic, username: username, email: email)
fetchedFriends.append(friend)
}
completion(fetchedFriends)
}
}else {
print(err!.localizedDescription)
completion(nil)
}
}
}
希望能有帮助