How to Generate a QR Code in Swift

Cloudmersive
2 min readMay 18, 2021

Originally developed for the automotive industry for tracking purposes, the QR code has come a long way since it first entered the scene. These days, QR codes can be spotted almost daily in our business transactions; their ability to be scanned by your mobile device to access websites, menus, forms, and more make them efficient and effective advertising tools. In today’s tutorial, we will demonstrate how you can use an API in Swift to generate a QR code image to be used for whatever purpose you require.

We will call the function with the following code, and the only inputs you will need are your API key and the text to convert into the QR code; this is often a URL or other free-form text.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)let parameters = "0=%3C&1=s&2=t&3=r&4=i&5=n&6=g&7=%3E"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/barcode/generate/qrcode")!,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()

And with that quick process, your QR code will be ready to roll! If you need to obtain an API key, you can do so by visiting the Cloudmersive website and registering for a free account; this will provide 800 monthly calls across any of our APIs.

--

--

Cloudmersive

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