Search code examples
swiftuitableviewmetadatareuseidentifierapi-linkpreview

How to set the metadata of LPLinkView to nil


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.


Solution

  • 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
                    }
                })
            }
        }
        
    }