【问题标题】:JSON returning when making requests in a for loop在 for 循环中发出请求时返回 JSON
【发布时间】: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,因为它们都是一样的。

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    不要自己管理索引变量,使用enumerated() API。

    在if let 检查之后运行enter 行

    var index:Int = 0

    for (index, notification) in self.notifications.enumerated() {
        if let supporter_id = notification.mainNotification?.supporter_id {
            myGroup.enter()
            GetUsersById2(id: supporter_id).getUser { user in
               self.notifications[index].supporter_info = user
               myGroup.leave()
            }
        }    
    }
    

    【讨论】:

    • 感谢您的回答。尽管对于某些循环,我仍然为零。有点混乱。
    • 在任何情况下,您都必须在getUser 中调用completion(例如使用Result 类型),否则组计数器会混淆。
    • 我以前从未在我的 GET 请求中使用过 Result,所以我不知道你的意思。您可以尝试在答案中写出代码吗?
    • 否则将闭包类型声明为(UsersModel?) -> (),并将所有出现的return 替换为completion(nil); return。在完成处理程序中检查 UsersModel 是否不是 nil 而是调用 always leave。
    • “在完成处理程序中检查 UsersModel 是否不为零但调用总是离开”。这是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多