在我的项目中,我通过调用一些API在UItableView中显示数据,我的tableView包含imageView,而对于它,我得到的是Image URL。
我已经进行了两次异步调用:
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所需的文本。现在我需要表内的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获取数据时将图像存储在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中显示。在以下链接中查找源
https://github.com/rs/SDWebImage

10-08 09:26
查看更多