问题
During the debugging of the code I tested the URL, that url works in the browser and the image is displayed in the browser. But the below code is not loading the image to the image wrapper.
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
回答1:
As explained in the comments, you can't return from an asynchronous task - you can't know when the task will be complete and when the data will be available.
The way to handle this in Swift is to use callbacks, often called by convention "completion handlers".
In this example I create a function to run the network task, and this function has a callback for when the image is ready.
You call this function with a syntax named "trailing closure" and there you handle the result.
Here's an example for you.
The new 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()
}
}
Your elements from your example:
let row = indexPath.row
cell.NewsHeading.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.NewsHeading.text = SLAFHeading[row]
And how you call the new 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
}
}
It's just an example to show how it works, so you might have to adapt to your app, but I believe it demonstrates what you need to do.
来源:https://stackoverflow.com/questions/36034479/i-am-calling-a-url-of-the-image-from-the-webservice-the-image-is-not-loaded-to