在我的项目中,我通过调用一些 API 在 UItableView
中显示数据,我的 tableView 包含 imageView,为此我正在获取图像 URL。
我进行了 2 次异步调用:
1) 用于从还包含 img URL 的 api 获取所有数据
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler:
{
(data,response,error) -> Void in
if error == nil && data != nil
{
do
{
let data1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray
dispatch_async(dispatch_get_main_queue())
{
// Here calling protocol and reloading UItable View
self.userInfoDelegate?.setUserInfo(data1)
}
}
catch
{
print("Something Went Wrong in REST")
}
}
}).resume()
到这里为止,我正在填充 UITableView 的必需文本。现在我需要 Table 中的 ImageView
也应该显示来自第一个 API 的 imagUrl 的图像
我正在进行另一个异步调用以获取 URL 的图像
func setUserInfo(data : NSMutableArray) {
var indexOf = 0
self.userTableView.reloadData()
for item in data
{
imageFromUrl(indexOf,urlString: to_pic,name:name )
indexOf = indexOf + 1
}
}
这是我获取图像的 NSData 并在获取数据时将图像存储在 UITableView 上的代码
func imageFromUrl(index : Int,urlString: String,name : String)
{
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let imgData = data
{
var image = UIImage?()
image = UIImage(data: imgData)
self.placeImage = image
}
if(self.placeImage == nil)
{
self.placeImage = UIImage(named: "User-2")
}
self.imageDictionary[index] = ["id":index,"image":self.placeImage!]
// ANother Asynch
dispatch_async(dispatch_get_main_queue())
{
if(self.imageDictionary.count == self.userArray.count)
{
for var newIndex in 0...self.imageDictionary.count - 1
{
self.setImageOnTableWithIndex(newIndex)
}
}
}
});
// do whatever you need with the task e.g. run
task.resume()
}
}
func setImageOnTableWithIndex(index : Int)
{
let indexPath = NSIndexPath(forRow: index, inSection: 0)
let cell = userTableView.cellForRowAtIndexPath(indexPath) as! UserListTableViewCell;
cell.userImageView.image = self.imageDictionary[index]!["image"] as? UIImage
}
它有时会正确显示图像,但大多数时候会在随机行上崩溃。我知道我必须正确处理许多异步调用,但无法找到正确的方法。
最佳答案
您可以使用 SDWebImage 异步下载图像并显示在 UIImageView 中。在以下链接中找到来源
关于ios - 如何在从 2 个不同 API 获取数据的 UITableView 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342603/