How to use the LinkPresentation Framework inside a Widget in SwiftUI to show an urlImage preview?

Here is an example code for a WidgetExtension that should show the link preview image retrieved using the LinkPresentation. I am guessing the widgets dont load url data directly but need to be somehow fetched using the geTimeline and defined there somehow? How is it done?

Using the standard widget template in Xcode just adding the Metadata

import WidgetKit
import SwiftUI
import LinkPresentation

struct SimpleEntry: TimelineEntry {
    let date: Date
}

struct LinkPresentationWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        //Text(entry.date, style: .time)
        VStack{
            MetadataView(vm: LinkViewModel(link: "https://www.wsj.com/articles/global-stock-markets-dow-update-03-03-2021-11614761029?mod=markets_lead_pos1"))
        }
    }
}




class LinkViewModel : ObservableObject {
    let metadataProvider = LPMetadataProvider()
    
    @Published var metadata: LPLinkMetadata?
    @Published var image: UIImage?
    
    init(link : String) {
        guard let url = URL(string: link) else {
            return
        }
        metadataProvider.startFetchingMetadata(for: url) { (metadata, error) in
            guard error == nil else {
                assertionFailure("Error")
                return
            }
            DispatchQueue.main.async {
                self.metadata = metadata
            }
            guard let imageProvider = metadata?.imageProvider else { return }
            imageProvider.loadObject(ofClass: UIImage.self) { (image, error) in
                guard error == nil else {
                    // handle error
                    return
                }
                if let image = image as? UIImage {
                    // do something with image
                    DispatchQueue.main.async {
                        self.image = image
                    }
                } else {
                    print("no image available")
                }
            }
        }
    }
}

struct MetadataView : View {
    @StateObject var vm : LinkViewModel
    
    var body: some View {
        VStack {
            if let uiImage = vm.image {
                Image(uiImage: uiImage)
                    .resizable()
                    //.scaledToFill()
                    //.clipped()
                    .frame(width: 60, height: 60)
            }
        }
    }
}


Read more here: https://stackoverflow.com/questions/66455246/how-to-use-the-linkpresentation-framework-inside-a-widget-in-swiftui-to-show-an

Content Attribution

This content was originally published by AndiAna at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: