Swift:确保在传递结果之前在我的函数中完成urlSession.dataTask

时间:2016-11-23 04:37:02

标签: swift xcode

您好我有这个功能:

func planAdded(id:Int, user_id:Int) -> Int {
    let locationURL = "myurl"
    var planResult: Int = 0
    let request = URLRequest(url: URL(string: locationURL)!)
    let urlSession = URLSession.shared
    let task = urlSession.dataTask(with: request, completionHandler:{
        (data, response, error) -> Void in

        DispatchQueue.main.async {

            if let error = error {
                print (error)
                return
            }

            if let data = data {

                let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                planResult = responseString!.integerValue

            }
        }


    })

    task.resume()
   print(planResult)

    return planResult
}

我要做的是确保我在indexpath函数的tableView cellforrow中得到了planResult的结果。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   ...
    case 4:



        if (result == 1){
           ...
        } else if (result == 2){
           ...
        } else {
           ...
        }


    default:
        cell.fieldLabel.text = ""
    }

    return cell

}

这是我的viewDidLoad函数

override func viewDidLoad() {
    super.viewDidLoad()
    self.result =  self.planAdded(1, 2)
}

由于某些原因,这会一直返回0;但是,打印线实际上是打印正确的值。我做了一些研究,我相信这是因为dataTask的asychonous调用。有没有办法确保我的函数实际完成并返回indexpath函数的值? 谢谢

1 个答案:

答案 0 :(得分:1)

原因是,你是以错误的方式做到的!因为,一旦初始化class UIViewController生命周期开始。调用viewDidLoad()后,UITableView也会更新,但没有数据。

此外,您正在调用API来获取数据,您需要通知UITableViewDataSource更新数据,以及如何执行此操作!

func planAdded(id:Int, user_id:Int) {
    let locationURL = "myurl"
    var planResult: Int = 0
    let request = URLRequest(url: URL(string: locationURL)!)
    let urlSession = URLSession.shared
    let task = urlSession.dataTask(with: request, completionHandler:{
        (data, response, error) -> Void in

        DispatchQueue.main.async {

            if let error = error {
                print (error)
                return
            }

            if let data = data {

                let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                self.result = responseString!.integerValue
                self.tableView.reloadData()
            }
        }
    })
    task.resume()
}

您获得zero价值,因为它是async方法。因此,获取使用completionCallback

所需的数据
func planAdded(id:Int, user_id:Int, completion: (result: Int) -> ()) {
    let locationURL = "myurl"
    var planResult: Int = 0
    let request = URLRequest(url: URL(string: locationURL)!)
    let urlSession = URLSession.shared
    let task = urlSession.dataTask(with: request, completionHandler:{
        (data, response, error) -> Void in

    DispatchQueue.main.async {

        if let error = error {
            print (error)
            return
        }

        if let data = data {

            let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            planResult = responseString!.integerValue
            completion(planResult)            
          }
        }
    })
    task.resume()
}
  

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    planAdded(1, 2){(value) in
        self.result = value
        self.tableView.reloadData()
    }
}