Link Preview in iOS with Open Graph Protocol Like WhatsApp
In WhatsApp, when you input a web link you get the preview of that link.+
How does this work?
If you think about this, you might probably get an idea that there is something to be fetch from or with a web link. When I first got to the question about how WhatsApp is working to display the link preview, I predicted there might be some open source public API to which we would feed the URL as parameter, then that API will return us JSON data containing image URL, name, description etc. This data we can bind to our UI and display it. Too Easy! But this was just one of the thoughts in my mind among hundreds. I started my research on the topic and didn’t find any API as such. What I found in my research is ‘Open Graph Protocol (OGP)’ as the base to work on the challenge. Next, I accepted the challenge and started adopting OGP.
We will directly see how OGP helped us display link preview in our app. To read more about what exactly the OGP is, please visit its official site: https://ogp.me/
At the time of reading the site, it mentioned there to “place additional <meta> tags in the <head> of your web page”. Please have a look at the screenshot. Our website bloomcs.com when inspected can show the meta tags with Open Graph properties (“og:title, og:site_name”, etc.)
There may be other properties too, like for Twitter and Facebook. In the above screenshot there are few twitter properties (e.g. “twitter:title”, “twitter:description”, etc.) that we can also scan for along with OGP properties.
Well, here is the logic in Objective-C:
- Use NSURLSession class to retrieve the source code for a given URL. You will get the whole HTML as a string.
- Use NSScanner to scan that HTML string for meta tags with required properties. In our case, the open graph properties.
- Scan ahead the detected meta tag for its content.
- Maintain the content in a key-value pair as NSDictionary.
- This way we will have the dictionary object at the end containing the required key-value pair. For example, the image key will have the image URL.
- Bind the collected data to an appropriate UI and we are done!
As I mentioned earlier, we could have an API for the same. We will have to write the same logic on the server, so then we can get required data for previewing the given link by simply feeding in that link as an input to the API. There are few server-side swift frameworks out there to let us run our swift code on server. One such popular among these frameworks is Vapor – https://vapor.codes/
I’ll try to develop the API using Vapor, publish it and share the experience in my future article 🙂