0

On the first View Controller I have a tableview that lists various sites like google, stack overflow... For each service added an image will load based on the first letter of that site. So an image of a T will load for Twitter.

If the user wants he/she can tap that cell and go to a 2nd VC and add the URL. When the user comes back to the first VC that site will try to pull the favicon instead of the letter image... this works, but not gracefully.

What I initially wanted was for each image to show up as soon as it loaded, obviously not all at once and not so it would disrupt the user interaction with the app.

What is happening now is that they show up a few at a time (which is ok) but not in the right place, initially. So say I have amazon, google, Microsoft, Facebook, and apple...the favicon would actually be out of order so Microsoft might have googles logo and after several seconds it might shift to Facebooks and then depending on how many there are it might shift again until it is all in the right matching place…This also happens if i scroll 'below the fold' and after several moments will right itself (the cell title remains in order however)

So I obviously have something in my code wrong, and would love, at the minimum, get it so it puts Facebook right the first time and then google, etc etc

OR another option could be all of the images START out as the letter image and then the code tries to replace it with the favicon...and get it right on the first try..

Any help would be great

Here is my Table View cellForRowAt code

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell", for: indexPath as IndexPath) as! ServiceTableViewCell
    let row = indexPath.row

    cell.serviceNameLabel.text = serviceArray[row].serviceName

    DispatchQueue.global().async {

      let myURLString: String = "http://www.google.com/s2/favicons?domain=\(self.serviceArray[row].serviceUrl)"

      if let myURL = URL(string: myURLString), let myData = try? Data(contentsOf: myURL), let image = UIImage(data: myData) {

        cell.serviceLogoImage.image = image

      } else {

        cell.serviceLogoImage.image = UIImage.init(named: "\(self.getLetterOrNumberAndChooseImage(text: self.serviceArray[row].serviceName))")

      }
    }
    return cell
  }
}
Community
  • 1
  • 1
RubberDucky4444
  • 2,330
  • 5
  • 38
  • 70

1 Answers1

1
cell.serviceLogoImage.image =  

Must be called from the Main Thread, since you are modifying User Interface.

Apple Documentation

Note For the most part, use UIKit classes only from your app’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your app’s user interface in any way.

Check this thread how to run the different threads from background and to the main.

Community
  • 1
  • 1