Swift 3-使用DispatchGroup()等待每个URL会话的完成?

Swift 3-使用DispatchGroup()等待每个URL会话的完成?,swift,asynchronous,swift3,synchronous,Swift,Asynchronous,Swift3,Synchronous,大家好,我遇到了这个问题,我有一个填充字符串的数组(例如:[dog,cat,girrafe,cow]),我将使用这个id对某个网站进行API调用,以从该网站获取图像。我需要结果与数组的顺序相同 对于本例,如果我打印两个数组,则需要输出如下: 串-狗、猫、女朋友、牛 年龄-5,10,20,5我建议您先用nil值初始化age: var age = [Int?](repeating: nil, count: theString.count) 然后,在每次调用完成后,将右索引处的值设置为您得到的结果

大家好,我遇到了这个问题,我有一个填充字符串的数组(例如:[dog,cat,girrafe,cow]),我将使用这个id对某个网站进行API调用,以从该网站获取图像。我需要结果与数组的顺序相同

对于本例,如果我打印两个数组,则需要输出如下: 串-狗、猫、女朋友、牛


年龄-5,10,20,5我建议您先用
nil
值初始化
age

var age = [Int?](repeating: nil, count: theString.count)
然后,在每次调用完成后,将右索引处的值设置为您得到的结果

    } else{
        do{

            let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
            let age = parsedData["age"] as! Int

            // Note these lines!
            if let index = theString.index(of: animal) {
                self.age[index] = age
            }

        } catch let error as NSError {
            print(error)
        }
    }//end else

我建议您首先用
nil
值初始化
age

var age = [Int?](repeating: nil, count: theString.count)
然后,在每次调用完成后,将右索引处的值设置为您得到的结果

    } else{
        do{

            let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
            let age = parsedData["age"] as! Int

            // Note these lines!
            if let index = theString.index(of: animal) {
                self.age[index] = age
            }

        } catch let error as NSError {
            print(error)
        }
    }//end else
试试这个

let theString = ["dog", "cat", "girraffe", "cow"]
var age = Array<Int>() // to store the ages of the animal in order

override func viewDidLoad() {
    super.viewDidLoad()
     //make the call 4 times
    for each in theString{
      doAPICall(animal: each,completion: { (responseArray,error) -> () in
           let age = responseArray["age"] as! Int
           if let index = theString.index(of: each) {
            self.age[index] = age
          }
        })
      print(age)//the output is in order 
    }
}
func doAPICall(animal: String,completion:@escaping (_ responsedata:NSDictionary?_ error:NSError?) -> Void){

  let Baseurl = "https://somewebsite.com/api/"+ animal
  let RequestUrl = URL(string: Baseurl)
  let request = NSMutableURLRequest(url: RequestUrl!)
  let semaphore = DispatchSemaphore(value: 0)
  let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

  guard error == nil && data != nil else {
            print("error=\(error?.localizedDescription)")
            return
        }
        if let httpStatus = response as? HTTPURLResponse{
            if httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
        }
        do {
            let ResponseDictionary = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as! as! NSDictionary?
            completion(ResponseDictionary,nil)
            semaphore.signal()
        }
        catch let error as NSError {
            print("Details of JSON parsing error:\n \(error.localizedDescription)")
            completion(nil,error)
        }
    }
    task.resume()
    _ = semaphore.wait(timeout: .distantFuture)
}
让字符串=[“狗”、“猫”、“女朋友”、“牛”]
var age=Array()//按顺序存储动物的年龄
重写func viewDidLoad(){
super.viewDidLoad()
//打4次电话
对于字符串中的每个{
DOAPCALL(动物:每个,完成:{(responseArray,error)->()在
让age=responseArray[“age”]as!Int
如果let index=字符串索引(of:each){
self.age[索引]=年龄
}
})
打印(年龄)//输出正常
}
}
func-doAPICall(动物:字符串,完成:@escaping(\uResponseData:NSDictionary?\uError:NSError?)->Void){
让Baseurl=”https://somewebsite.com/api/“+动物
让RequestUrl=URL(字符串:Baseurl)
let request=NSMutableURLRequest(url:RequestUrl!)
让信号量=分派信号量(值:0)
让task=session.dataTask(其中:request作为URLRequest){(数据、响应、错误)在
保护错误==nil&&data!=nil else{
打印(“错误=\(错误?.localizedDescription)”)
返回
}
如果让httpStatus=响应为?HTTPURLResponse{
如果httpStatus.statusCode!=200{
打印(“状态代码应为200,但为\(httpStatus.statusCode)”)
打印(“响应=\(响应)”)
}
}
做{
让ResponseDictionary=try JSONSerialization.jsonObject(使用:data!as data,选项:.allowFragments)作为!as!NSDictionary?
完成(负责人,无)
信号量
}
将let错误捕获为NSError{
打印(“JSON解析错误的详细信息:\n\(error.localizedDescription)”)
完成(无,错误)
}
}
task.resume()
_=信号量。等待(超时:.distantFuture)
}
像这样试试

let theString = ["dog", "cat", "girraffe", "cow"]
var age = Array<Int>() // to store the ages of the animal in order

override func viewDidLoad() {
    super.viewDidLoad()
     //make the call 4 times
    for each in theString{
      doAPICall(animal: each,completion: { (responseArray,error) -> () in
           let age = responseArray["age"] as! Int
           if let index = theString.index(of: each) {
            self.age[index] = age
          }
        })
      print(age)//the output is in order 
    }
}
func doAPICall(animal: String,completion:@escaping (_ responsedata:NSDictionary?_ error:NSError?) -> Void){

  let Baseurl = "https://somewebsite.com/api/"+ animal
  let RequestUrl = URL(string: Baseurl)
  let request = NSMutableURLRequest(url: RequestUrl!)
  let semaphore = DispatchSemaphore(value: 0)
  let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

  guard error == nil && data != nil else {
            print("error=\(error?.localizedDescription)")
            return
        }
        if let httpStatus = response as? HTTPURLResponse{
            if httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
        }
        do {
            let ResponseDictionary = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as! as! NSDictionary?
            completion(ResponseDictionary,nil)
            semaphore.signal()
        }
        catch let error as NSError {
            print("Details of JSON parsing error:\n \(error.localizedDescription)")
            completion(nil,error)
        }
    }
    task.resume()
    _ = semaphore.wait(timeout: .distantFuture)
}
让字符串=[“狗”、“猫”、“女朋友”、“牛”]
var age=Array()//按顺序存储动物的年龄
重写func viewDidLoad(){
super.viewDidLoad()
//打4次电话
对于字符串中的每个{
DOAPCALL(动物:每个,完成:{(responseArray,error)->()在
让age=responseArray[“age”]as!Int
如果let index=字符串索引(of:each){
self.age[索引]=年龄
}
})
打印(年龄)//输出正常
}
}
func-doAPICall(动物:字符串,完成:@escaping(\uResponseData:NSDictionary?\uError:NSError?)->Void){
让Baseurl=”https://somewebsite.com/api/“+动物
让RequestUrl=URL(字符串:Baseurl)
let request=NSMutableURLRequest(url:RequestUrl!)
让信号量=分派信号量(值:0)
让task=session.dataTask(其中:request作为URLRequest){(数据、响应、错误)在
保护错误==nil&&data!=nil else{
打印(“错误=\(错误?.localizedDescription)”)
返回
}
如果让httpStatus=响应为?HTTPURLResponse{
如果httpStatus.statusCode!=200{
打印(“状态代码应为200,但为\(httpStatus.statusCode)”)
打印(“响应=\(响应)”)
}
}
做{
让ResponseDictionary=try JSONSerialization.jsonObject(使用:data!as data,选项:.allowFragments)作为!as!NSDictionary?
完成(负责人,无)
信号量
}
将let错误捕获为NSError{
打印(“JSON解析错误的详细信息:\n\(error.localizedDescription)”)
完成(无,错误)
}
}
task.resume()
_=信号量。等待(超时:.distantFuture)
}

您可以使用补全block@bhupatBheda你能详细说明一下吗?我确实查看了完成块,并在这里看到了一些示例,但我无法完全理解实现。我是一个新手,你能告诉我你的目的你到底想做什么吗?所以现在你正在调用api,并希望以相同的顺序响应?我基本上有一个tableview,它显示视频游戏的比赛历史。我需要按照最近匹配的顺序存储数据。每个匹配都有相应的图标。为了得到这个图标,我需要用matchID作为输入进行API调用,它会给我字符串,这样我就可以将它存储在一个变量中。但很明显,为了按顺序打印图标,我必须按与matchID数组相同的顺序存储它。但事实并非如此,因为异步调用可以在任何时候完成。我只是用动物来简化问题。你可以用补全block@bhupatBheda你能详细说明一下吗?我确实查看了完成块,并在这里看到了一些示例,但我无法完全理解实现。我是一个新手,你能告诉我你的目的你到底想做什么吗?所以现在你正在调用api,并希望以相同的顺序响应?我基本上有一个tableview,它显示视频游戏的比赛历史。我需要按照最近匹配的顺序存储数据。每个匹配都有相应的图标。要获得该图标,我需要使用matchID作为输入进行API调用,然后