使用Core Image filter来保证类型安全

swift 更新日常官方不给文档,正常操作。

0X00

以前进行二维码生成的时候,代码一般如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import CoreImage
enum CorrectionLevel: String {
case L, M, Q, H
}
func generateQRCode (
for content: String, correctionLevel: CorrectionLevel = .M) -> CIImage {
let data = content.data(using: .utf8)!
let level = correctionLevel.rawValue
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(data, forKey: "inputMessage")
qrFilter.setValue(level, forKey: "inputCorrectionLevel")
return qrFilter.outputImage!
}
generateQRCode(for: "perphet.com")

但问题来了,如果你把inputMessage 写错了,或者传错了 correctionLevel 的值,编译不报错,你也很难检查出来,纯属恶心人。

0X01

自从iOS13更新之后,官方也更新了一些东西,但方法更新了,不给你文档,也不告诉你,甚至 Xcode 的自动补全功能里根本就没这个功能,正常操作,不愧是苹果😑

现在添加

1
import CoreImage.CIFilterBuiltins

新代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import CoreImage
enum CorrectionLevel: String {
case L, M, Q, H
}
func generateQRCode (
for content: String, correctionLevel: CorrectionLevel = .M) -> CIImage {
let data = content.data(using: .utf8)!
let level = correctionLevel.rawValue
let qrFilter = CIFilter.qrCodeGenerator()
qrFilter.message = data
qrFilter.correctionLevel = level
return qrFilter.outputImage!
}
generateQRCode(for: "perphet.com")

1571756124.png

Title: 使用Core Image filter来保证类型安全

Author: Tuski

Published: 10/22/2019 - 22:25:53

Updated: 10/22/2019 - 22:57:07

Link: http://www.perphet.com/2019/10/使用Core-Image-filter来保证类型安全/

Protocol: Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) Reprinted please keep the original link and author

Thx F Sup