Is there a way to generate QR code image on iOS

后端 未结 8 2093
-上瘾入骨i
-上瘾入骨i 2020-12-22 19:59

Is there a standard way to generate a QR code and attach it to a mail item from iOS client app (no server code)?

8条回答
  •  粉色の甜心
    2020-12-22 20:35

    It has been a while since this question was asked and a number of almost perfect answers have been given already. However I had to tweak and combine several answers to get it working perfectly for AppleTV 4K, iPhone X and iPadPro using Xcode 9.2 in 2018. Here's the code if anyone needs it.

    @IBOutlet weak var qrCodeBox: UIImageView!
    
    func createQRFromString(_ str: String, size: CGSize) -> UIImage {
        let stringData = str.data(using: .utf8)
    
      let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
      qrFilter.setValue(stringData, forKey: "inputMessage")
      qrFilter.setValue("H", forKey: "inputCorrectionLevel")
    
      let minimalQRimage = qrFilter.outputImage!
      // NOTE that a QR code is always square, so minimalQRimage..width === .height
      let minimalSideLength = minimalQRimage.extent.width
    
      let smallestOutputExtent = (size.width < size.height) ? size.width : size.height
      let scaleFactor = smallestOutputExtent / minimalSideLength
      let scaledImage = minimalQRimage.transformed(
        by: CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
    
      return UIImage(ciImage: scaledImage, 
                     scale: UIScreen.main.scale, 
                     orientation: .up)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let myQRimage = createQRFromString("https://www.apple.com", 
                          size: qrCodeBox.frame.size)
        qrCodeBox.image = myQRimage
    }
    

提交回复
热议问题