Last active
March 17, 2021 05:25
-
-
Save kraigspear/4531d7faa2b0b8cffad996988a74e8e8 to your computer and use it in GitHub Desktop.
Generate A QR Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// QRCodeGeneration.swift | |
// TempCheck | |
// | |
// Created by Kraig Spear on 6/12/20. | |
// | |
import CoreImage.CIFilterBuiltins | |
import UIKit | |
/// Type that can generate a QRCode from a string | |
protocol QRCodeGeneratable { | |
/** | |
Generate a QRCode from a string | |
- parameter from: String to generate a QRCode from | |
- returns: Image of QRCode or xmark.circle if there were any errors creating the QRCode | |
*/ | |
func generate(from string: String) -> UIImage | |
} | |
/** | |
Implementation of `QRCodeGeneratable` | |
Generates a QRCode from a String | |
*/ | |
final class QRCodeGeneration: QRCodeGeneratable { | |
/** | |
Generate a QRCode from a string | |
- parameter from: String to generate a QRCode from | |
- returns: Image of QRCode or xmark.circle if there were any errors creating the QRCode | |
*/ | |
func generate(from string: String) -> UIImage { | |
let context = CIContext() | |
let filter = CIFilter.qrCodeGenerator() | |
let data = Data(string.utf8) | |
filter.setValue(data, forKey: "inputMessage") | |
if let outputImage = filter.outputImage { | |
if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) { | |
return UIImage(cgImage: cgimg) | |
} | |
} | |
return UIImage(systemName: "xmark.circle") ?? UIImage() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment