ios - (Swift) 在 for 循环中使用带有 NSURLSession 的信号量

标签 ios swift semaphore nsurlsession

我目前正在尝试从 for 循环中的多个 GET 请求下载数据,然后将其添加到 TableView 中。 我成功获取了数据,但遇到的问题是主线程在从请求下载所有数据之前一直运行,因此它没有加载到 TableView 中。 我正在尝试使用信号量尝试一次运行一个线程,但它似乎不起作用。 这是代码:

for item in array{
    let http = item["http"] as! String
    let URL = NSURL(string: http)
    let Request = NSMutableURLRequest(url: URL! as URL)
    Request.setValue(self.headerVal, forHTTPHeaderField: "Authorization")
    Request.httpMethod = "GET"
    let UrlSession = URLSession.shared
    let Info = UrlSession.dataTask(with: Request as URLRequest) { (data, response, error) -> Void in
        if error != nil{
            print(error!)
            return;
        }
        else{
            do{
                let ResponseData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
                guard let results = ResponseData["data"] as? [Any] else {
                    print("Couldnt get response from \(http)")
                    return
                }
                let Result = results[0] as! [String:Any]
                self.result.append(Result)
            }
            catch{
                print(error)
            }
        }
    }
    Info.resume()

}
print("finished")
self.tableView.reloadData()

如何才能在请求中的所有数据下载完成后刷新我的表格 View ?

最佳答案

Semaphore 是一种方法,但 DispatchGroup 可能是更好的方法。

 let downloadGroup = DispatchGroup()
 for item in array{
  ...
 downloadGroup.enter()
let Info = UrlSession.dataTask(with: Request as URLRequest) { (data, response, error) -> Void in
  ...
  downloadGroup.leave()
  }   
 }   

 downloadGroup.notify(queue: DispatchQueue.main) { // 2
   //callback
 }   

关于ios - (Swift) 在 for 循环中使用带有 NSURLSession 的信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45062671/

相关文章:

objective-c - 使用 CFWriteStream 将文件传输到套接字

ios - .xib 文件中 UITableViewCell 中的 UILabel 忽略暗模式

swift - 在一行中打印带有换行符的字符串作为文本 ("example\n example")

ios - 色调正在快速反转颜色

c++ - "Semaphore must not be currently signaled or in a wait state"

ios - 向图像添加多行文本区域

ios - iOS 应用程序中的 SQLITE_BUSY 错误

ios - Swift - Firebase 数据库查询项目范围

c - sem_post 的段错误

linux-kernel - 关于 linux 内核中的信号量 up() 和 mutex_unlock()