McAPI - Screenshot API with Swift 5

Swift sample code to capture website screenshots with the McAPI Screenshot REST API service. We provide an iOS Playground that you can use for testing, download. The sample uses Swift 5, the playground requires Xcode 12.4 or higher.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the snippets below with your RapidAPI key.

All samples below work with the free tier of the API, see RapidAPI McAPI Screenshot Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Take a screenshot using Swift 5

In the first sample, we take a screenshot of the Indiehackers website. The device is set to Default (viewPort size = 1024x768px). With the storeExternal option set to "false", the screenshot will be returned as a base64 encoded JPEG.

The source code:

// Swift 5
  
import Foundation
import UIKit

let headers = [
  "content-type": "application/json",
  "x-rapidapi-key": "YOUR_API_KEY",
  "x-rapidapi-host": "mcapi-screenshot.p.rapidapi.com"
]

let parameters = [
  "url": "https://indiehackers.com",
  "storeExternal": "false",
  "format": "jpeg",
  "devices": [ "Default" ],
] as [String : Any]

let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://mcapi-screenshot.p.rapidapi.com/")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  }
  else {
    let httpResponse = response as? HTTPURLResponse
    if httpResponse?.statusCode == 200{
      if let data = data{
        ...
      }
    }
    else{
      // handle 400 errors here, see documentation for possible error conditions
    }
  }
})

dataTask.resume()

The response will be delivered as a JSON formatted string in data, see further below for sample code that shows how to parse the data:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://indiehackers.com",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB ... 9yXvZG0pSuhyP/9k="
    }
  ]
}

McAPI Screenshot API - Sample screenshot with Swift 5

The returned image from the Swift request:

Image of McAPI Screenshot API Sample Screenshot Swift

Specifying devices

The Screenshot API contains a built-in database of over one hundred predefined devices and screen sizes. To get a list of all devices use the listDevices option, like so:

// Swift 5
  
...

let parameters = [
  "listDevices": "true"
] as [String : Any]

...

The API will now return an array of all known devices, here's an excerpt:

{
  "devices": [

    ...
  
    { "name": "iPhone 12 mini", "width": 375, "height": 812 },
    { "name": "iPhone 12 mini landscape", "width": 812, "height": 375 },
    { "name": "iPhone 12", "width": 390, "height": 844 },
    { "name": "iPhone 12 landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro", "width": 390, "height": 844 },
    { "name": "iPhone 12 Pro landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro Max", "width": 428, "height": 926 },
    { "name": "iPhone 12 Pro Max landscape", "width": 926, "height": 428 },

    ...
  ]
}

Internally, the API also maintains proper User Agent-strings for the respective device, not shown in the list.

Specifying a predefined device is simple, just set its name in the call. In this example we want the screenshot as it would appear on an iPhone 12:

// Swift 5
  
...

let parameters = [
  "url": "https://mcapi.io",
  "devices" : [ "iPhone 12" ]
] as [String : Any]

...

The devices param is an array; to create multiple screenshots at once, specify additional devices (the current limit is five):

// Swift 5
  
...

let parameters = [
  "url": "https://mcapi.io",
  "devices" : [ "iPhone 12", "iPhone 12 landscape" ]
] as [String : Any]

...

Note that specifying multiple devices will cause the API to load the target URL for each device and then take a screenshot; this can take some time with "heavy" or slow sites and may cause your code to timeout; see the discussion on timeouts.

Specifying viewports

If none of the predefined devices and screen sizes are suitable for your application, you can specify your own viewport:

// Swift 5
  
...

let parameters = [
  "url": "https://mcapi.io",
  "viewPort" : { "width": 800, "height": 600 }
] as [String : Any]

...

This will create a screenshot with 800x600px; if a viewport is specified, the API will use a generic desktop User agent-string when loading the target URL.

Note that the viewPort option is ignored if a devices array is also specified.

Cookie consent banners and ad blocking

If so desired, the API can also automatically click the "Accept", "Accept all" or similar buttons on DSGVO / GDPR cookie warnings (Note that this feature is currently experimental, see discussion.)

Consider this screenshot of the CNBC.com site with default API settings. The site displays a very prominent banner:

Screenshot API - Cookie Consent Banner Swift

Set the cookie option to "true" like so:

// Swift 5
  
...

let parameters = [
  "url": "https://cnbc.com",
  "cookie": "true",
  "devices" : [ "Default" ]
] as [String : Any]

...

The screenshot now shows the site without the banner.

Screenshot API - Clicked Cookie Banner and Ad with Swift

Blocking ads in screenshots

Sometimes you will want to take screenshots with ads, for instance to check ad placement or rotation. However, in most cases you want the screenshots to capture the site as intended by the designers, i.e. without any ads. The screenshot API comes with a built-in ad blocker, activate it like so:

// Swift 5
  
...

let parameters = [
  "url": "https://cnbc.com",
  "cookie": "true",
  "adblock": "true",
  "devices" : [ "Default" ]
] as [String : Any]

...

The CNBC website without cookie warning and without ads:

Screenshot API - Clicked Cookie Banner and Ad blocked Swift

The header-parameter - writing screenshots to a file (Swift)

With the storeExternal option set to "false", the screenshot image is returned as a base64 encoded string. Per default, this string is preceded by a header that describes the media type (or MIME) of the string.

Sample data block for a screenshot, to be returned as a PNG:

// Swift 5

...

let parameters = [
  "url": "https://mcapi.io",
  "storeExternal": "false",
  "format": "png"
] as [String : Any]

...

The result will look like this:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/jpeg;base64,iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

To parse the JSON string, we set up two auxiliary structs, Screenshot and Result, that declare the fields that the API returns (Note that both structs must conform to the Decodable protocol in order for the JSON parser to work.) After decoding you can then directly set the "screenshot"-string as the src property of an img tag. This is particularly useful if you want to load screenshots into a web view, like so:

// Swift 5

...

struct Screenshot : Decodable{
  let device: String
  let screenshot: String
}

struct Result : Decodable{
  let service: String
  let version: String
  let url: String
  let screenshots: [Screenshot]
}

...

if httpResponse?.statusCode == 200{
  if let data = data{
    let result: Result = try! JSONDecoder().decode(Result.self, from: data)
    // result.screenshots[0].screenshot now holds the screenshot as a base64 encoded PNG image
    // In real life you would iterate over the result.screenshots array
    let screenshot = result.screenshots[0].screenshot
    let img = "<img src=\"" + screenshot + "\""/>"
    webView.loadHTMLString(img)
  }
}

...

The MIME header will make sure that the image data is interpreted correctly by the web view or browser. However, when writing the image data to a JPEG or PNG file, including the header would result in an invalid file. To create a screenshot image without the header, set the header option to "false", like so:

// Swift 5

...

let parameters = [
  "url": "https://mcapi.io",
  "storeExternal": "false",
  "format": "png",
  "header": "false"
] as [String : Any]

...

The returned screenshot image without header:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

Now, all we have to do is decode the base64 string and then create an UIImage from the PNG data. Shown here as a complete example (this is the contents of the provided Playground, see link in the introduction):

// Swift 5

import Foundation
import UIKit

struct Screenshot : Decodable{
  let device: String
  let screenshot: String
}

struct Result : Decodable{
  let service: String
  let version: String
  let url: String
  let screenshots: [Screenshot]
}

let headers = [
  "content-type": "application/json",
  "x-rapidapi-key": "YOUR_API_KEY",
  "x-rapidapi-host": "mcapi-screenshot.p.rapidapi.com"
]

let parameters = [
  "url": "https://indiehackers.com",
  "storeExternal": "false",
  "format": "png",
  "header": "false",
  "devices": ["Default"]
] as [String : Any]

let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://mcapi-screenshot.p.rapidapi.com/")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  }
  else {
    let httpResponse = response as? HTTPURLResponse
    if httpResponse?.statusCode == 200{
      if let data = data{
        let result: Result = try! JSONDecoder().decode(Result.self, from: data)
        // In production code you would iterate over result.screenshots
        if let pngData = Data(base64Encoded: result.screenshots[0].screenshot, options: .ignoreUnknownCharacters){
          let img = UIImage(data: pngData);
        }
      }
    }
    else{
      // handle 400 errors here, see documentation for possible error conditions
    }
  }
})

dataTask.resume()

Back to McAPI Screenshot API main page.