Swift-代码未为外部闭包返回数组值

时间:2018-07-26 04:28:17

标签: swift uitableview asynchronous networking closures

我的快速代码有问题。我试图在任务关闭之外获取YearsLinks数组的值,但是由于返回空数组,所以我无法这样做,我理解这是因为代码在完成关闭之前先运行print(yearsLinks)代码。

我需要做些什么方面的帮助,有人建议使用异步,但是我不确定应该在哪里以及如何实现它。

请帮助 我想设置数组值,并链接到tableview中的单元格。

这是我的代码的摘要。感谢帮助。非常感谢:)

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var url = String()
var yearsLinks = [String]()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return yearsLinks.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
    cell.textLabel?.text = yearsLinks[indexPath.row]
    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if let requests = URL(string: url){
        let request = NSURLRequest(url: requests)
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            if error != nil {
                print(error as Any)
            } else {
                if let unwrappedData = data {
                    let wrappedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

                              ...
              //  THESE ARE JUST CODE TO GRAB THE ARRAY THAT I WANT
              //  linkyears IS AN ARRAY OF VALUES DECLARED IN THE CLOSURE THAT I WANT TO SET TO THE yearsLinks VARIABLE DECLARED OUTSIDE.          
                        self.yearsLinks = linkyears
                              ...

                        print(self.yearsLinks) // THIS WORKS FINE AND RETURNS AN ARRAY OF VALUES THAT I WANTED.
                    }
                }
            }

        }
         // print(yearsLinks)
        // TRYING TO ACCESS THE ARRAY OF VALUES IN THE yearsLinks ARRAY ABOVE RETURNS AN EMPTY STRING??

        task.resume()

    }
}

}

1 个答案:

答案 0 :(得分:0)

获取完成块内的数据后,需要重新加载表视图。

if let unwrappedData = data {
    let wrappedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

              ...
        DispatchQueue.main.async {
            self.yearsLinks = linkyears
            print(self.yearsLinks)
            self.tableView.reloadData()
        }
    }
}