Search code examples
iosswiftshare-extension

Get data from Share Extension in Swift


Inside my app I have a CustomShareViewController and with that the workflow should be like this:

  1. User is in Safari on some website and looks up any kind of product

  2. User taps on "share" and selects my App

  3. I parse data from the current URL and use it/store it inside my app

Problem:

How do I get the data in Swift? I managed to get the current URL and with that the HTML like this:

@objc func actionButtonTapped(){

        var html: String?

        if let item = extensionContext?.inputItems.first as? NSExtensionItem,
            let itemProvider = item.attachments?.first,
            itemProvider.hasItemConformingToTypeIdentifier("public.url") {
            itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
                if (url as? URL) != nil {

                    html = (self.getHTMLfromURL(url: url as? URL))

                    self.doStuff(html: html)
                }
            }
        }
}

But is there any way to get the data that Apple provides? (image and title) ?

That's the data from Apple I mean:

enter image description here


Solution

  • With @Filip's hint I found this Git-Repo:

    URLEmbeddedView

    With this I can simply get the data like this:

    let urlString = ...
    OpenGraphDataDownloader.shared.fetchOGData(urlString: urlString) { result in
        switch result {
        case let .success(data, isExpired):
            // do something
        case let .failure(error, isExpired):
            // do something
        }
    }