ios - 使用调度等待数据附加到数组?
问题描述
我试图从 Firestore 下载数据,将其附加到一个要排序的数组,然后在所有数据都排序后将其附加到另一个数组。我有一个调度组,它在继续之前管理正在下载的所有数据,但是我不知道如何或在哪里将排序数组(temparray1 / temparray2)附加到主数组(closeunisSameCourse/nearbyUnis)。我曾尝试使用 dispatch.wait 来等待两个临时数组被附加,但它只是挂起。
func nearbyUnisSameCourse(completion: @escaping (_ success: Bool) -> Void) {
DispatchQueue.main.async {
self.spinner.startAnimating()
}
self.dispatchGroup.enter()
service.loadUniversityAndCourse { (uni, course) in
defer{ self.dispatchGroup.leave() }
let nearbyUnis = ClosestUnis()
let closeUniArray = nearbyUnis.getClosestUnis(University: uni)
for uni in closeUniArray {
let UniRef = Firestore.firestore().collection("User-Universities").document(uni)
self.dispatchGroup.enter()
UniRef.getDocument { (snapshot, error) in
defer{ self.dispatchGroup.leave() }
if let error = error{
print(error.localizedDescription)
}
else {
//append their data to an array
guard let data = snapshot?.data() else {return}
let stringArray = Array(data.keys)
for user in stringArray {
self.dispatchGroup.enter()
let usersRef = Firestore.firestore().collection("users").document(user)
usersRef.getDocument { (snapshot, error) in
defer{ self.dispatchGroup.leave() }
if let error = error {
print(error.localizedDescription)
}
else {
let data = snapshot?.data()
if let dictionary = data as [String:AnyObject]? {
let Info = UserInfo(dictionary: dictionary)
if Info.Course == course {
print(Info.username!)
self.tempArray1.append(Info)
self.tempArray1.sort { (time1, time2) -> Bool in
return Double(time1.Created!.seconds) > Double(time2.Created!.seconds)
}
self.closeunisSameCourse.append(contentsOf: self.tempArray1)
self.tempArray1.removeAll()
}
else {
self.tempArray2.append(Info)
print(Info.username!)
self.tempArray2.sort { (time1, time2) -> Bool in
return Double(time1.Created!.seconds) > Double(time2.Created!.seconds)
}
}
}
}
}
//end of for user loop
}
//outside user for loop
print("now appending")
self.nearbyUnis.append(contentsOf: self.tempArray2)
print(self.nearbyUnis.description)
self.tempArray2.removeAll()
}}}}
self.dispatchGroup.notify(queue: .main) {
print("Finished")
//self.spinner.stopAnimating()
//print(self.nearbyUnis.description)
self.tableView.reloadData()
completion(true)
}
}
}
解决方案
按名称排序固定
else {
self.nearbyUnis.append(Info)
print(Info.username!)
self.nearbyUnis.sort { (time1, time2) -> Bool in
return Double(time1.Created!.seconds) >
Double(time2.Created!.seconds)}
self.nearbyUnis.sort { (uni1, uni2) -> Bool in
return uni2.University! > uni1.University!}
}
推荐阅读
- spring-boot - Spring Boot中的Jetty自定义格式日志模式
- python - adb - 在 android 设备中获取应用程序名称(设置 > 应用程序)#python
- workflow - Alfresco 工作流 api 正在丢失一个变量
- shell - 使用 kubectl 和 pg_dump 将数据库转储下载到本地
- javascript - 在 React JS 中将 PDF 转换为图像 [.JPG]
- java - 使用 Java JSOUP 抓取网站时如何下载静态文件
- javascript - 在Angular中单击时如何更改按钮的文本
- windows - 如何获得 terraform 供应商窗口的 cacert 验证
- react-native - 任务错误:app:mergeReleaseResources FAILED
- android - 使用 logcat Android Studio 记录错误