【发布时间】:2020-08-11 18:36:57
【问题描述】:
所以我在我的数组 for 循环 (loadSupporter(completion: @escaping(()->())) 中发出 GET 请求。它为每个循环获取正确的数据,除了最后 3-6 个循环。
import Foundation
import UIKit
class NotificationVC: Toolbar, UITableViewDelegate, UITableViewDataSource {
var notifications:[NotificationViewModel] = [] {
didSet {
loadSupporter(completion: {
self.myTableView.reloadData()
})
}
}
override func viewDidLoad() {
loadNotifications()
}
func loadNotifications() {
print("loadNotifications")
if let user_id = profile?.sub {
let getNotifications = GETNotificationsByUserID(user_id: user_id)
getNotifications.getNotifications { notifications in
self.notifications = notifications.map { notification in
let ret = NotificationViewModel()
ret.mainNotification = notification
return ret
}
}
}
}
func loadSupporter(completion: @escaping(()->())) {
let myGroup = DispatchGroup()
var index:Int = 0
for notification in self.notifications {
myGroup.enter()
if let supporter_id = notification.mainNotification?.supporter_id {
GetUsersById2(id: supporter_id).getUser { user in
self.notifications[index].supporter_info = user
index += 1
myGroup.leave()
}
}
}
myGroup.notify(queue: .main) {
completion()
}
}
//Web Service
import Foundation
class GetUsersById2 {
var id:String
var dataTask:URLSessionDataTask?
init(id:String) {
self.id = id
}
func getUser(completion: @escaping (UsersModel) -> ()) {
var components = URLComponents()
components.scheme = "https"
components.host = "dev-owihjaep.auth0.com"
components.path = "/api/v2/users/\(id)"
let url = components.url
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET"
let accessToken = AccessToken().accessToken
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
dataTask = URLSession.shared.dataTask(with: request) { data, _, error in
if let error = error {
print("Error Getusersbyid2 \(error)")
return
}
guard let data = data else {
return
}
guard let user = try? JSONDecoder().decode(UsersModel.self, from: data) else {
print("Unable to decode responseData")
return
}
DispatchQueue.main.async {
completion(user)
print("GetUsersById2 user \(user)")
}
}
dataTask?.resume()
}
}
我知道这不是 supporter_id 传递到 url,因为它们都是一样的。
【问题讨论】: