Screenshot a URL in Swift

Cloudmersive
2 min readAug 2, 2021

Have you or your colleagues ever received an email with a suspicious or unknown URL? Instead of taking an unnecessary risk by clicking the link, why not take a screenshot of it to ensure that it’s safe first? In this tutorial, we will show you to use an API in Swift to fully render a website and generate a PNG screenshot of the full-page — this will allow you to determine the safety level of the site prior to an actual interaction with the URL.

Before we call the screenshot function, you will need the screenshot request parameters:

{
"Url": "string",
"ExtraLoadingWait": 0,
"ScreenshotWidth": 0,
"ScreenshotHeight": 0
}

Once you have the required parameters, we can call the function with the following code:

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)let parameters = "Url=%3Cstring%3E&ExtraLoadingWait=%3Cinteger%3E&ScreenshotWidth=%3Cinteger%3E&ScreenshotHeight=%3Cinteger%3E"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/convert/web/url/to/screenshot")!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()

That’s all there is to it! Simple.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.