Swift Link Preview

Friday, 24 June 2016

I gotta confess that I got obsessed on trying to port my first Link Preview project to other platforms. I made it! First to Android, then a reboot using newer technologies and now it’s finally on Swift!

Swift is a great programming language that allows us to learn faster and build more stuff in less time because of its simplicity.

Back then, when I created my first project related to previewing link, only Facebook had this feature on their services. Now many companies preview links inside their products. None of them has open-sourced it though.

It basically does the same thing as the others. It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.

Visual Examples

   
Swift Link Preview Example 1 Swift Link Preview Example 2
Swift Link Preview Example 3 Swift Link Preview Example 4

Swift Link Preview Example 5

Requirements and Details

  • iOS 9.0+ / macOS 10.11+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+
  • Built with Swift 3.0

Installation

CocoaPods

To use SwiftLinkPreview as a pod package just add the following in your Podfile file.


source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'Your Target Name' do
    use_frameworks!
    // ...
    pod 'SwiftLinkPreview', '~> 1.0.1'
    // ...
end

Carthage

To use SwiftLinkPreview as a Carthage module package just add the following in your Cartfile file.


// ...
github "LeonardoCardoso/SwiftLinkPreview" ~> 1.0.1
// ...

Swift Package Manager

To use SwiftLinkPreview as a Swift Package Manager package just add the following in your Package.swift file.


import PackageDescription
let package = Package(
  name: "Your Target Name",
  dependencies: [
    // ...
    .Package(url: "https://github.com/LeonardoCardoso/SwiftLinkPreview.git", "1.0.1")
    // ...
  ]
)

Manually

You just need to drop SwiftLinkPreview folder into Xcode project (make sure to enable “Copy items if needed” and “Create groups”).

Usage

Instantiating


import SwiftLinkPreview
// ...
let slp = SwiftLinkPreview(
    session: URLSession = URLSession.shared,
    workQueue: DispatchQueue = SwiftLinkPreview.defaultWorkQueue,
    responseQueue: DispatchQueue = DispatchQueue.main,
    cache: Cache = DisabledCache.instance
)

Requesting preview


slp.preview("Text containing URL",
            onSuccess: { result in print("\(result)") },
            onError: { error in print("\(error)")})

The result is a dictionary [String: AnyObject] like:


Response {
	let url: URL // URL
	let finalUrl: URL // unshortened URL
	let canonicalUrl: String // canonical URL
	let title: String // title
	let description: String // page description or relevant text
	let images: [String] // array of URLs of the images
	let image: String // main image
	let icon: String // favicon
	let video: String // video
	let price: String // price
}

Cancelling a request

 
let cancelablePreview = slp.preview(...,
                                    onSuccess: ...,
                                    onError: ...)
cancelablePreview.cancel()

Enabling and accessing cache

SLP has a built-in memory cache, so create your object as the following:


let slp = SwiftLinkPreview(cache: InMemoryCache())

To get the cached response:


if let cached = self.slp.cache.slp_getCachedResponse(url: String) {
    // Do whatever with the cached response
} else {
	// Perform preview otherwise
	slp.preview(...)
}

If you want to create your own cache, just implement this protocol and use it on the object initializer.


public protocol Cache {
    func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response?

    func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?)
}

Flow

Swift Link Preview Flow

Important

You need to set Allow Arbitrary Loads to YES on your project’s Info.plist file.

Swift Link Preview Configuration 1

If you don’t want to use the option above and you are using SwiftLinkPreview for services of your knowledge, you can whitelist them on Info.plist file as well. You can read more about it here, here and here.

Swift Link Preview Configuration 2

Tips

Not all websites will have their info brought, you can treat the info that your implementation gets as you like. Here are two tips about posting a preview:

  • If some info is missing, you can offer the user to enter it. Take for example the description.
  • If more than one image is fetched, you can offer the user the feature of picking one image.

License

The MIT License


This code is also available on my GitHub profile.

GitHub Starred Repos Downloader »