Swift 如何使用计数器多次调用dataTask方法?

Swift 如何使用计数器多次调用dataTask方法?,swift,swift5,Swift,Swift5,我目前正在使用SwiftUI开发一个应用程序 我想使用while方法、标志和计数器多次调用dataTask方法 但是我的代码不起作用 如何解决这个问题 这是我的密码: func makeCallWithCounter(){ var counter = 0 var flag = false // Set up the URL request let endpoint: String = "

我目前正在使用SwiftUI开发一个应用程序

我想使用
while
方法、标志和计数器多次调用
dataTask
方法

但是我的代码不起作用

如何解决这个问题


这是我的密码:

func makeCallWithCounter(){
        
        var counter = 0
        var flag = false
        
        // Set up the URL request
        let endpoint: String = "https://sample.com/api/info/"
        
        guard let url = URL(string: endpoint) else {
            print("Error: cannot create URL")
            return
        }
        var urlRequest = URLRequest(url: url)
        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        
        // make the request
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            // parse the result as JSON, since that's what the API provides
            DispatchQueue.main.async {
                do{ self.sample = try JSONDecoder().decode([Sample].self, from: responseData)
                    
                    counter += 1
                    
                    if counter > 4 {
                        flag = true
                    }
                }catch{
                    print("Error: did not decode")
                    return
                }
            }
        }
        while flag == false {
            task.resume()
        }
    }
已更新

func makeCallWithCounter(){

var day = 1
var date = "2020-22-\(day)"
var totalTemperature = 0
var counter = 0
var flag = false

// Set up the URL request
let endpoint: String = "https://sample.com/api/info/?date=\(date)"

guard let url = URL(string: endpoint) else {
    print("Error: cannot create URL")
    return
}
var urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

// make the request
let task = session.dataTask(with: urlRequest) {
    (data, response, error) in
    // parse the result as JSON, since that's what the API provides
    DispatchQueue.main.async {
        do{ self.sample = try JSONDecoder().decode([Sample].self, from: responseData)
            
            day += 1
            totalTemperature += self.sample.temperature
            
            if day > 4 {
                flag = true
            }
        }catch{
            print("Error: did not decode")
            return
        }
    }
 }
while flag == false {
    task.resume()
 }
print(totalTemperature)
}


Xcode:12.0.1版

正如我在评论中所写,您需要一个循环和
调度组
。另一方面,您不需要
标志
计数器
,实际上甚至不需要
URLRequest

我删除了冗余代码,但仍然存在一个严重错误:行

totalTemperature += sample.temperature
如果
sample
是数组,则无法工作。该问题包含的信息不足,无法解决此问题

func makeCallWithCounter() {
    
    var totalTemperature = 0
    let group = DispatchGroup()
    for day in 1...4 {
        // Set up the URL request
        let endpoint = "https://sample.com/api/info/?date=2020-22-\(day)"
        
        guard let url = URL(string: endpoint) else {
            print("Error: cannot create URL")
            continue
        }
        
        // make the request
        group.enter()
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            defer { group.leave() }
            if let error = error { print(error); return }
            // parse the result as JSON, since that's what the API provides
            do {
                let sample = try JSONDecoder().decode([Sample].self, from: data!)
                totalTemperature += sample.temperature
            } catch {
                print(error)
            }
        }
        task.resume()
    }
    
    group.notify(queue: .main) {
        print(totalTemperature)
    }
}

代码执行一次任务,
标志
,计数器无效。要多次执行该任务,您需要一个循环和
DispatchGroup
。那么多次调用同一个URL的目的是什么?@vadian,我更新了我的代码,作为新代码,我希望每次在
while
roop中使用不同的URL调用该方法。所以,如果我只调用
DispatchGroup
,它就不能像我想的那样工作,对吗?