McAPI - QR API Swift for iOS / macOS

Swift sample code to create QR barcodes with the McAPI QR REST API service. We provide a 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 with your own api key.

The sample can be used with the free tier of the API, see RapidAPI McAPI QR Listing for available plans.

See the overview page for available parameters and error codes.

Create QR code using Swift

Shown is the creation of a QR code with Swift encoding the URL https://mcapi.io. The code is created in red (dot color) and blue (finder color) with a dot size of 10 pixels. The dot style is set to "1" (for separated dots), the shape is set to "1" (for dots in disc or circle shape). The output format is "png". As the QR error correction is not specified, the API will use ECC level "M", sufficient for most purposes. Use "Q" (numeric value "3") for highest error correction capability.

import Foundation

struct Result : Decodable{
  let service: String
  let version: String
  let format: String
  let code: String
}

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

let parameters = [
	"data": "https://mcapi.io",
	"dotSize": 10,
	"finderColor": "#0000FF",
	"dotColor": "#FF0000",
	"dotStyle": 1,
	"dotShape": 1,
	"format": "png"
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://mcapi-qr.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 qr: Result = try! JSONDecoder().decode(Result.self, from: data)
        // qr.code holds the QR code as a base64 encoded PNG
        // For converting to UIImage/NSImage see https://stackoverflow.com/questions/11251340
        print(qr.code)
      }
    }
    else{
      // handle 400 errors here, see documentation for possible error conditions
    }
  }
})

dataTask.resume()

For parsing the result, the sample defines the struct Result as Decodable, the barcode will be in the code property of the parsed result. In this example the barcode will be delivered as a base64 encoded PNG which can be directly injected into the src property of an img tag in a Webview. Alternatively, it can be converted to a UIImage / NSImage, see for example here.

McAPI QR API - Sample QR barcode with Swift

The returned code from the request:

Image of McAPI QR API Sample Barcode Swift

Encoding UTF-8 characters and text in QR codes with Swift

Swift will handle UTF-8 characters or strings out of the box (for example german "umlauts", e.g. "ÄÖÜ", or non-latin script, e.g. "日本語"). Here's a snippet with the same QR settings as above but with Unicode content (umlauts and some japanese kanjis):

...

let parameters = [
	"data": "123456abcdefÄÖÜ日本語",
	"dotSize": 10,
	"finderColor": "#0000FF",
	"dotColor": "#FF0000",
	"dotStyle": 1,
	"dotShape": 1,
	"format": "png"
] as [String : Any]

...

The generated QR code with Unicode content:

Image of McAPI QR API Sample Barcode Unicode Swift

Scanning QR codes

It's recommended to test scan the created QR codes. On iOS, the built-in camera app will natively detect and scan QR codes in the camera's view. For Android, use Google's Zxing Barcode Scanner app (free). Both apps will scan from the computer display, no need to print the codes.

Back to McAPI QR API main page.