Swift 4:使用URLSession发出请求并更新全局变量

时间:2018-05-27 05:55:01

标签: json multithreading api swift4 nsurlsessiondatatask

我正在编写一个应用程序,通过进行API调用来获取对总线的预测。在我的例子中,有5条总线路由,我想循环以修改每个API端点,然后拨打电话。我通过以下方式在viewdidload方法中执行此操作:

  1. 在课堂上,我有一个全局词典,其中的键是路径ID
  2. 在viewdidload中,我遍历这个字典并调用一个返回闭包的方法来更新字典:

    for routeid in prioritized_routes_with_stops.keys {
        let temp_val = prioritizedRoutesHelper (completion: {lst in
            self.prioritized_routes_with_stops[routeid] = lst
        }, routeid: routeid)//all I do here is set a value for the key routeid
        print (prioritized_routes_with_stops) //ISSUE
    
  3. 此处如果是辅助方法,则优先级为RouteHelper:

    func prioritizedRoutesHelper(completion: @escaping (((String, String), Int, Int)) -> (), routeid: String) {
        let formatted_url = "https://api.umd.io/v0/bus/routes/\(routeid)/arrivals/\(user_dict[routeid]!.0)"
        guard let url = URL(string: formatted_url) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else {return}
            let dataAsString = String(data: data, encoding: .utf8)
            if (dataAsString?.contains("dirTitleBecauseNoPredictions"))!  == true{
                var temp = (("a", ""), 0, 0)//placeholder to see if update to "a"
                completion(temp)//ignore else case...
    
  4. 所以,我的问题如下 - 为什么在步骤2中的for循环之后,当我打印更新的字典时,没有更新任何值。例如,如果我在闭包中打印字典中的值,它会打印正确的值,但是当我循环遍历所有routeids后打印全局变量时,它还没有更新? 谢谢!

1 个答案:

答案 0 :(得分:0)

您要发出一组异步请求,建议您使用DispatchGroup,因此,在for routeid in prioritized_routes_with_stops.keys {之前添加:

let group = DispatchGroup()

然后添加:

group.enter()

然后在self.prioritized_routes_with_stops[routeid] = lst之前的完成闭包中添加:

group.leave()

最后是:

group.notify(queue: .main) {
    print (prioritized_routes_with_stops)
}