【问题标题】:Why does the completion handler does not return anything?为什么完成处理程序不返回任何内容?
【发布时间】:2020-01-22 13:58:45
【问题描述】:

所以,我有一个 json 获取请求,它获取类 Horse 的所有马对象。这成功了。我有一个完成处理程序,它应该让我在另一个视图中再次使用 horses 对象,在该视图中我调用 getHorses 请求,但是当我尝试将这些对象放入另一个数组时,它不会附加它们。为什么会这样?

这是我的代码:

func getJSONHorses (completion: @escaping ([Horse])->[Horse]) { //Message<[Horse]>
          let url = "http://localhost:8083/horses"
      if let url = URL(string: url)
      {
          let task = session.dataTask(with: url) { data, response, error in

                    if error != nil || data == nil {
                        print("Client error!")
                        return
                    }
              let str = String(decoding: data!, as: UTF8.self)
              print(str)
                    do {
                     print("nothing")

                      let json = try JSONDecoder().decode(Message<[Horse]>.self, from: data!)

                        print(json.model?.count as Any)
                     // print(json.model as Horse)
                    //  print(json.self.model)
                    //  print(json.model)

                      print(json.model as Any)
                      print("something")
                        completion(json.model!)


                    } catch {
                        print("JSON error: \(error)")
                      print("erroooorrrrrr")
                    }
                }

                task.resume()
          print("finished")

      }
  }

这里我使用函数:

print("Startttt")
    backEnd.getJSONHorses(completion:{(horse) in
            for h in horse {
                self.horses.append(h)
            }
        print(horse.count)
           self.horses = horse
            //print(horse.count as Any
            return horse
        })

    print(horses.count)
    print("END")

即使我尝试将马附加到其中,马数组也是 0。

【问题讨论】:

  • 你打印horses.count 之前完成处理程序被调用...
  • 第二个print(horses.count) 运行时,马还没有被提取。只需删除第二个打印语句,因为完成处理程序中已经有一个。
  • 是的,但是如何正确获取它们以便可以在表格中显示它们。目前,不会显示。即使是第一个 print(horses.count ) 也不会显示在终端中
  • @MartinR 我们真的需要想出一些经典的方法来回答这些问题。问题的描述很简单,解决方案的处方真的很难。很难回答深入研究建筑的问题。
  • 我很确定已经给出了一些“在异步获取数据后重新加载表视图”

标签: swift completion


【解决方案1】:

我已经用previous data(JSON 和实现)测试了你的代码,首先,我建议使用这个:

func getJSONHorses(completion: @escaping([Horse]) -> Void)

您应该为 UITableViewDelegate, UITableViewDataSource 准备逻辑(tableView 取决于您的数组,并且您设置 numberOfRowsInSectionself.horses.count 等)并将 tableView 的数据设置为某个变量(就像您所做的那样 - self.horses 其中它是全局的var horses = [Horse]()),只需调用它:

backEnd.getJSONHorses(completion:{ horse in
    print(horse.count)
    self.horses = horse
    self.tableView.reload()
})

就是这样。我已经检查过了,已经足够了。并且要小心 - 你应该在收到数据后重新加载表格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2012-04-02
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多