這個demo的主要功能是用于防止有人浪用接口赠潦,頻繁的去請求接口带族。實現(xiàn)的主要原理如下:
1.創(chuàng)建一個用來驗證的字符串
func getAuthcode() {
codeArray = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for _ in 0..<6//需要多少個字符來驗證
{
let num = codeArray.count-1
let y = Int(arc4random_uniform(UInt32(num)))
let tempStr = codeArray[y]
if codeString == nil {
codeString =? tempStr
}else{
codeString = codeString! +? tempStr
}}}
2.為這個字符串創(chuàng)建一個視圖?
override func draw(_ rect: CGRect) {
super.draw(rect)
self.backgroundColor = UIColor.init(red: CGFloat(Double(arc4random()%256)/256.0) , green:? CGFloat(Double(arc4random()%256)/256.0) , blue:? CGFloat(Double(arc4random()%256)/256.0) , alpha: 1.0)
let cSize = ("A" as NSString).size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20)])
let width = rect.size.width/CGFloat((codeString! as NSString).length) - cSize.width
let height = rect.size.height - cSize.height
var point:CGPoint?
var x:CGFloat = 0.0
var y:CGFloat = 0.0
for index in 0..<(codeString! as NSString).length {
x = CGFloat(arc4random_uniform(UInt32(width))) + rect.size.width/CGFloat((codeString! as NSString).length)*CGFloat(index)
y = CGFloat(arc4random_uniform(UInt32(height)))
point = CGPoint.init(x: x, y: y)
let? c = (codeString! as NSString).character(at: index)
let textC:String = String(Character(UnicodeScalar(c)!))
(textC as NSString).draw(at: point!, withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: CGFloat(arc4random_uniform(UInt32(5)) + 15))])
}
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(1.0)
for _ in 0..<5//線條數(shù)量
{
let color =? UIColor.init(red: CGFloat(Double(arc4random()%256)/256.0) , green:? CGFloat(Double(arc4random()%256)/256.0) , blue:? CGFloat(Double(arc4random()%256)/256.0) , alpha: 1.0)
context?.setStrokeColor(color.cgColor)
x = CGFloat(arc4random_uniform(UInt32(rect.size.width)))
y = CGFloat(arc4random_uniform(UInt32(rect.size.height)))
context?.move(to: CGPoint.init(x: x, y: y))
x = CGFloat(arc4random_uniform(UInt32(rect.size.width)))
y = CGFloat(arc4random_uniform(UInt32(rect.size.height)))
context?.addLine(to: CGPoint.init(x: x, y: y))
context?.strokePath()
}}
3.為這個視圖添加觸摸手勢,可以讓其更換視圖
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
codeString = nil
self.getAuthcode()
self.setNeedsDisplay()
}
4》最后的效果如下: