简体   繁体   English

Swift 3 - 未调用完成处理程序

[英]Swift 3 - completion handler not called

EDIT: I'm using Swift 3.0 and Alamofire 4.0 编辑:我正在使用Swift 3.0和Alamofire 4.0

In my system I have a list of materials, each material contain a list of bundles. 在我的系统中,我有一个材料列表,每个材料都包含一个包列表。 Im trying to request these bundles via webservice and then populate the next view (in this example I'm trying to only print the data fetched), but my Completion Handler is not being called (ps: i'm beginner and that's the first time i'm leading with async prog). 我试图通过webservice请求这些包,然后填充下一个视图(在这个例子中我只是尝试打印所提取的数据),但我的完成处理程序没有被调用(ps:我是初学者,这是第一次我用异步编程领导。 Any idea why? 知道为什么吗?

The function that fetch data from WS is: 从WS获取数据的函数是:

  func fetchBundles(materialCode: String, completion: @escaping ([ProductsBundle]?) -> Void ) {
    var bundlesAdded = [ProductsBundle]()
    let url = baseApiURL + "material-cavaletes/" + materialCode
    print(url)

    Alamofire.request(url, headers: headers).responseJSON {
      response in
      if let result = response.result.value {
        var results = JSON(result)["results"]

        for res in results {
          bundlesAdded.append(self.getBundleFromJson(json: res))
        }

        completion(bundlesAdded)
      }
    }
  }

And the function call ,that should get the data and update the view, is: 并且应该获取数据并更新视图的函数调用是:

WebApi.sharedInstance.fetchBundles(materialCode: materialBeingListed.id, completion: {
  (bundlesAdded: [ProductsBundle]?) in
  guard let myBundles = bundlesAdded else {
    print("erro")
    return
  }

  print (myBundles)
})

I put some breakpoint at the code and noticed that the line "print (myBundles)" is never being called. 我在代码中添加了一些断点,并注意到“print(myBundles)”这一行从未被调用过。 I have no clue why... :( 我不知道为什么... :(

I think you might be handling your Alamofire request incorrectly. 我想你可能错误地处理了你的Alamofire请求。 Try this: 尝试这个:

Alamofire.request(url, headers: headers).responseJSON {
  response in
    switch response.result {
      case .success(let data):
        let json = JSON(data)
        print("JSON: \(json)")
        break
      case .failure(let error):
        print("Fetch failed :( error: \(error.localizedDescription)")
        switch(error._code) {
          case NSURLErrorTimedOut:
            print("Timed Out")
          default:
            print(error._code)
        }
    }
}

Once you see what the JSON data looks like you should be able to access it correctly. 一旦看到JSON数据的样子,您就应该能够正确访问它。 Typically JSON becomes a Dictionary when you unserialize it. 通常,当您对其进行反序列化时,JSON将成为一个Dictionary。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM