0

I'm using LPLinkView in a tableview cell. While scrolling the reused cell initially displays the LinkProvider of the recycled cell and then changes as soon as the network call completes. I want to prepare the cell for reuse. Is there a way to set the link providers metadata to nil? (similar to imagview.image = nil)

I'll do it in the prepareForReuse function.

Saad Rehman
  • 363
  • 1
  • 7
  • 18

1 Answers1

1

You can do it like this -

class MyTableViewCell: UITableViewCell {
    let linkView = LPLinkView(frame: .zero)
    var metadataProvider = LPMetadataProvider()
    
    override func prepareForReuse() {
        super.prepareForReuse()
        
        // Cancel in-flight metadata fetch request
        metadataProvider.cancel()

        // Assign an empty metadata object, all properties inside this are nil
        linkView.metadata = LPLinkMetadata()
    }
    
    func populateData(json: [String: Any]) {
        if let link = json["link"] as? String, let url = URL(string: link) {
            metadataProvider = LPMetadataProvider()
            metadataProvider.startFetchingMetadata(for: url, completionHandler: { [weak self] (metadata, error) in
                if let metadata = metadata, error == nil {
                    self?.linkView.metadata = metadata
                }
            })
        }
    }
    
}
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • Just tried it, this throws as error: Terminating app due to uncaught exception 'NSGenericException', reason: 'Trying to start fetching on an LPMetadataProvider that has already started. LPMetadataProvider is a one-shot object.' – Saad Rehman Jun 14 '21 at 14:28
  • 1
    It just says that `LPMetadataProvider` should not be reused. Every time you start fetching metadata, just create a new instance of `LPMetadataProvider`. See the EDIT to the answer. – Tarun Tyagi Jun 14 '21 at 14:32
  • Thanks for the edit. Performance still isn't optimal for some reason (it shows the old cell's url without the icons for a brief moment before changing) – Saad Rehman Jun 14 '21 at 14:34
  • 1
    Setting an empty metadata object is the best we can do - we can't force a UI refresh on `LPLinkView`. What you can do is - hide this view until metadata has been fetched and show it after the assigning the metadata. While this is hidden, you could show any placeholder, activityIndicator view to indicate the load is in progress. – Tarun Tyagi Jun 14 '21 at 14:37