我正在调用web服务的图像的url。 该图像没有加载到uitableview

在debugging代码的过程中,我testing了URL,该URL在浏览器中运行,图像显示在浏览器中。 但是下面的代码不会将图像加载到图像包装器。

let row = indexPath.row cell.NewsHeading.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) cell.NewsHeading.text = SLAFHeading[row] if let url = NSURL(string: SLAFImages[indexPath.row]) { let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in if error != nil { print("thers an error in the log") } else { dispatch_async(dispatch_get_main_queue()) { cell.NewsImage.image = UIImage(data: data!) } } } task.resume() } return cell 

正如注释中所解释的那样,您不能从asynchronous任务返回 – 您无法知道任务何时完成以及数据何时可用。

在Swift中处理这个问题的方法是使用callback函数,通常被称为“完成处理程序”。

在这个例子中,我创build了一个函数来运行networking任务,这个函数有一个callback,当图像准备就绪时。

您可以使用名为“trailing closure”的语法来调用该函数,然后处理结果。

这是你的一个例子。

新function:

 func getNewsImage(stringURL: String, completion: (image: UIImage)->()) { if let url = NSURL(string: stringURL) { let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in if error != nil { print(error!.localizedDescription) } else { if let data = data { if let image = UIImage(data: data) { completion(image: image) } else { print("Error, data was not an image") } } else { print("Error, no data") } } } task.resume() } } 

你的例子中的元素:

 let row = indexPath.row cell.NewsHeading.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) cell.NewsHeading.text = SLAFHeading[row] 

以及如何调用新function:

 getNewsImage(SLAFImages[indexPath.row]) { (image) in dispatch_async(dispatch_get_main_queue()) { cell.NewsImage.image = image // here you update your UI or reload your tableView, etc } } 

这只是一个例子来说明它是如何工作的,所以你可能不得不适应你的应用程序,但是我相信它certificate了你需要做什么。