虽然在某些应用程序中没有必要添加验证码,因为应用程序不像网页那样容易受到机器人的攻击。因此,在我的看法中,有些应用程序并不需要添加验证码来防止机器人的攻击。但如果你确实需要嵌入验证码,可以尝试以下代码:
使用以下输出口和变量:
NSArray *arrCapElements;
IBOutlet UILabel *Captcha_label;
IBOutlet UITextField *Captcha_field;
IBOutlet UILabel *Status_label;
以及 IBActions
为:
- (IBAction)Reload_Action:(id)sender;
- (IBAction)Submit_Action:(id)sender;
arrCapElements = [[NSArray alloc]initWithObjects:@"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", nil];
加载验证码的代码:
-(void)load_captcha{
@try {
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
Captcha_label.backgroundColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
//Captcha_label.textColor=[UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
NSUInteger elmt1,elmt2,elmt3,elmt4,elmt5,elmt6;
elmt1 = arc4random() % [arrCapElements count];
elmt2= arc4random() % [arrCapElements count];
elmt3 = arc4random() % [arrCapElements count];
elmt4 = arc4random() % [arrCapElements count];
elmt5 = arc4random() % [arrCapElements count];
elmt6 = arc4random() % [arrCapElements count];
NSString *Captcha_string = [NSString stringWithFormat:@"%@%@%@%@%@%@",arrCapElements[elmt1-1],arrCapElements[elmt2-1],arrCapElements[elmt3-1],arrCapElements[elmt4-1],arrCapElements[elmt5-1],arrCapElements[elmt6-1]];
//NSLog(@" Captcha String : %@",Captcha_string);
Captcha_label.text = Captcha_string;
}
@catch (NSException *exception) {
NSLog(@"%@",exception);
}
}
- (IBAction)Reload_Action:(id)sender {
[self load_captcha];
}
检查验证码是否正确:
- (IBAction)Submit_Action:(id)sender {
NSLog(@"%@ = %@",Captcha_label.text,Captcha_field.text);
if([Captcha_label.text isEqualToString: Captcha_field.text]){
[self.view endEditing:YES];
Status_label.text =@"Success";
Status_label.textColor = [UIColor greenColor];
}else{
Status_label.text =@"Faild";
Status_label.textColor = [UIColor redColor];
}
}
它将会显示如下:
参考来源:iOS验证码生成器
虽然我们在iOS上没有任何验证码的API,甚至reCaptcha也没有为iOS提供任何插件。很多人建议我不需要为移动应用程序实现验证码。我同意了,但是由于客户不能听取任何借口,我所做的就是:
简单地使用以下代码创建随机数:
-(NSInteger)randomIntBetween:(NSInteger)min and:(NSInteger)max
{
return (NSInteger)(min + arc4random_uniform(max + 1 - min));
}
将该数字放置在标签上,并要求用户在提供的文本字段中输入相同的数字。如果找到匹配项,则完成了验证码的主要部分[另一端的用户是唯一集成验证码的人类],否则我会重新生成随机数并再次将其放置在标签上,要求用户在提供的文本字段中输入相同的数字。
最终结果将如下所示。