文档中心 > 阿里聚安全

数据风控-iOS示例代码

更新时间:2017/02/14 访问次数:939
//
//  RootVC.m
//  MSAuthSDK
//
//  Created by Jeff Wang on 16/3/13.
//  Copyright ? 2016年 Jeff Wang. All rights reserved.
//

#import "RootVC.h"
#pragma mark 需要引入的头文件
#import <MSAuthSDK/MSAuthVCFactory.h>
#import <SecurityGuardSDK/Open/OpenSecurityGuardManager.h>
#import <SecurityGuardSDK/Open/OpenSecurityBody/IOpenSecurityBodyComponent.h>
#import <SecurityGuardSDK/Open/OpenSecurityBody/OpenSecurityBodyDefine.h>
#import <SecurityGuardSDK/Open/OpenSecurityBody/IOpenSecurityBodyComponent.h>

@protocol textSelectDelegate
-(void)onSelect:(UITextField*)v index:(NSUInteger)index;
@end
@interface UITextFieldWithPick:UITextField<UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)NSArray<NSString*>* choise;
@property(nonatomic,weak)id<textSelectDelegate> selectDelegate;
@end
@implementation UITextFieldWithPick
{
    int pickindex;
    int oldindex;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
//    self.delegate = self;
    return self;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 1;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.choise.count;
}


- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.choise objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component
{
    pickindex = row;
}


- (void)showAuthChoose {
    oldindex = pickindex;
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    
    [pickerView sizeToFit];
    pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator = YES;
    self.inputView = pickerView;
    
    
    
    
    UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
    keyboardDoneButtonView.barStyle = UIBarStyleDefault;
    keyboardDoneButtonView.translucent = YES;
    keyboardDoneButtonView.tintColor = nil;
    [keyboardDoneButtonView sizeToFit];
    
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                target:self
                                                                                action:@selector(pickerDoneClicked)] ;
    UIBarButtonItem* doneButton1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                 target:self
                                                                                 action:@selector(pickerCancelClicked)] ;
    
    
    [keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton,doneButton1, nil]];
    self.inputAccessoryView = keyboardDoneButtonView;
    
    
}
/*
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self==textField) {
        return NO;
    }
    return TRUE;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (textField==self) {
//        [self showAuthChoose];
    }
    return YES;
}
*/
-(void)pickerCancelClicked
{
    self.text = [self.choise objectAtIndex:self->oldindex];
    [self endEditing:TRUE];
}
-(void)pickerDoneClicked
{
    self.text = [self.choise objectAtIndex:self->pickindex];
    [self endEditing:TRUE];
    [self.selectDelegate onSelect:self index:pickindex];
}

@end



@interface RootVC () <MSAuthProtocol,textSelectDelegate>
@property (nonatomic, strong) NSString *currentLanguage;
@property (nonatomic, strong) UITextField* ipaddress;
@property (nonatomic, strong) UITextFieldWithPick* chooseAuth;
@property (nonatomic, strong) UITextFieldWithPick* chooseAuthNoneNum;
@property (nonatomic, assign) NSInteger chooseAuthNoneNumIndex;
@property (nonatomic, strong) UITextField* phonenumber;
@property (nonatomic, strong) UITextView* status;
@property (nonatomic,copy)NSString* host;
@property (nonatomic,copy)NSString* phonetext;
@property (nonnull,strong)NSArray* choice;

@end

@implementation RootVC
    {
        MSAuthType mAuthType;
        NSInteger  pickindex;
    }
-(void)setColor
{
    self.view.backgroundColor = [UIColor whiteColor];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"验证SDK demo ";
    }
    return self;
}
-(void)msgNotSupport
{
    [self verifyDidFinishedWithResult:VERIFY_REUSLT_FAIL Error:[NSError errorWithDomain:@"暂不支持" code:-1 userInfo:nil] SessionId:nil];

}
#pragma mark 选择方式
-(void)fengkongAndShibie
{
    switch (self->mAuthType) {
        case MSAuthTypeSlide:
        case MSAuthTypeCall:
        case MSAuthTypeSms:
            [self pushAuthVC:self->mAuthType];
            break;
            
        default:
            [self msgNotSupport];
            return;
    }
}
-(void)yanzheng
{
    MSAuthType type = 0;
    switch (self.chooseAuthNoneNumIndex) {
        case 0:
            type = MSAuthTypeSlide;break;
        case 1:
            type = MSAuthBallRoll;
        case 2:
            type = MSAuthBallShake;
        default:
            [self msgNotSupport];
            return;
    }
    [self onAuthType:type data:nil];
}
-(void)onSelect:(UITextField*)v index:(NSUInteger)index
{
    if (v==self.chooseAuth) {
        self->mAuthType = index;
    }
    else if(v == self.chooseAuthNoneNum)
    {
//      self.chooseAuthNoneNum.choise = @[@"划一划",@"滚一滚",@"摇一摇"];
        self.chooseAuthNoneNumIndex = index;
        
    }

}
- (void)viewDidLoad {
    [self setColor];
#define  space  0
#define  height 35
#define  label_height    20
#define  leading         10
#define  controlwidth    self.view.bounds.size.width-40-40
//    MSAuthTypeSms       =1,
//    MSAuthTypeCall,
//    MSAuthTypeMail,
//    MSAuthTypeSlide,
//    MSAuthBallShake,
//    MSAuthBallRoll
    self.choice= @[@"切换语言",@"短信",@"语音",@"滑动",@"邮件",@"摇一摇",@"滚动"];

    UILabel*  l = [[UILabel alloc] initWithFrame:CGRectMake(leading, 80, controlwidth, label_height)];
    l.font = [UIFont systemFontOfSize:10];
    l.text = @"服务器地址/域名";
    [self.view addSubview:l];
    self.ipaddress = [[UITextField alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(l.frame) ,controlwidth, height)];
    self.ipaddress.clearButtonMode= UITextFieldViewModeWhileEditing;
    self.ipaddress.textAlignment =  NSTextAlignmentCenter;
    [self.ipaddress setBorderStyle:UITextBorderStyleRoundedRect];

    NSString* ip = [[NSUserDefaults standardUserDefaults] valueForKey:@"ip"];
    if (ip.length) {
        self.host = ip;
    }
    else
    {
        self.host =  @"0.0.0.0";
    }
    self.ipaddress.text = self.host;
    [self.view addSubview:self.ipaddress];
//    self.ipaddress.delegate = self;
    [self.ipaddress addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    

    l = [[UILabel alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(self.ipaddress.frame)+space, controlwidth, label_height)];
    l.font = [UIFont systemFontOfSize:10];
    l.text = @"电话号码";
    [self.view addSubview:l];
    
    
    self.phonenumber = [[UITextField alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(l.frame), controlwidth, height*1)];
    self.phonenumber.clearButtonMode= UITextFieldViewModeWhileEditing;
    [self.phonenumber setBorderStyle:UITextBorderStyleRoundedRect];
    self.phonetext = [[NSUserDefaults standardUserDefaults] valueForKey:@"phone"];
    self.phonenumber.text = self.phonetext;
    [self.phonenumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.phonenumber];
    
    

    
    
    
    
    l = [[UILabel alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(self.phonenumber.frame)+space, controlwidth, label_height*1)];
    l.font = [UIFont systemFontOfSize:10];
    l.text = @"风险识别+验证";
    [self.view addSubview:l];

    
    self.chooseAuth = [[UITextFieldWithPick alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(l.frame), controlwidth, height*1)];
    self.chooseAuth.selectDelegate = self;
    self.chooseAuth.delegate = self;
    self.chooseAuth.choise = self.choice;
    self->mAuthType = MSAuthTypeSlide;
    self.chooseAuth.text = [self.choice objectAtIndex:self->mAuthType];
    [self.chooseAuth setBorderStyle:UITextBorderStyleRoundedRect];
    [self.view addSubview:self.chooseAuth];
    
    UIButton* b = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.chooseAuth.frame)+10,
                                                             CGRectGetMaxY(l.frame),
                                                            self.view.bounds.size.width-CGRectGetMaxX(self.chooseAuth.frame)-15,
                                                             height*1)
                   ];
    [b.titleLabel setFont:[UIFont systemFontOfSize:10]];
    [b.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [b.layer setCornerRadius:2];
    [b.layer setBorderWidth:1];
    [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [b setTitle:@"识别+验证" forState:UIControlStateNormal];
    [b addTarget:self action:@selector(fengkongAndShibie) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b];

    l = [[UILabel alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(self.chooseAuth.frame)+space, controlwidth, label_height*1)];
    l.font = [UIFont systemFontOfSize:10];
    l.text = @"风险验证";
    [self.view addSubview:l];
    self.chooseAuthNoneNum = [[UITextFieldWithPick alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(l.frame), controlwidth, height*1)];
    self.chooseAuthNoneNum.selectDelegate = self;
    self.chooseAuthNoneNum.delegate = self;
    self.chooseAuthNoneNumIndex = 0;
    self.chooseAuthNoneNum.choise = @[@"滑动",@"滚一滚",@"摇一摇"];
    self.chooseAuthNoneNum.text = @"滑动";
    [self.chooseAuthNoneNum setBorderStyle:UITextBorderStyleRoundedRect];
    [self.view addSubview:self.chooseAuthNoneNum];

    

    
    b = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.chooseAuthNoneNum.frame)+10,
                                                             CGRectGetMaxY(l.frame),
                                                             self.view.bounds.size.width-CGRectGetMaxX(self.chooseAuthNoneNum.frame)-15,
                                                             height*1)
                   ];
    [b.titleLabel setFont:[UIFont systemFontOfSize:10]];
    [b.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [b.layer setCornerRadius:2];
    [b.layer setBorderWidth:1];
    [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [b setTitle:@"验证" forState:UIControlStateNormal];
    [b addTarget:self action:@selector(yanzheng) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b];
    
    
    l = [[UILabel alloc] initWithFrame:CGRectMake(leading, CGRectGetMaxY(self.chooseAuthNoneNum.frame)+space, controlwidth, label_height)];
    l.font = [UIFont systemFontOfSize:10];
    l.text = @"回调返回错误信息";
    [self.view addSubview:l];
    
    
    self.status = [[UITextView alloc] initWithFrame:CGRectMake(leading,
                                                               CGRectGetMaxY(l.frame),
                                                               controlwidth,
                                                               CGRectGetMaxY(self.view.frame)- CGRectGetMaxY(l.frame)-10)];
    
    [self.status setEditable:NO];
    self.status.layer.backgroundColor = [[UIColor clearColor] CGColor];
    self.status.layer.borderColor =  [[UIColor lightGrayColor]  CGColor];
    self.status.layer.borderWidth = 1.0;
    self.status.layer.cornerRadius = 3.0f;
    self.status.text = @"";
    [self.view addSubview:self.status];
    
#pragma mark 设置运行环境,默认是线上
    [super viewDidLoad];
}
-(void)textFieldDidChange :(UITextField *)theTextField{
    if(theTextField==self.ipaddress){
        self.host= theTextField.text;
    }
    if(theTextField==self.phonenumber){
        self.phonetext= theTextField.text;
        [[NSUserDefaults standardUserDefaults] setValue:self.phonetext forKey:@"phone"];
    }

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField==self.ipaddress)
    {
        [textField resignFirstResponder];
        return YES;
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (textField==self.chooseAuth) {
        [self.chooseAuth showAuthChoose];
    }
    else if (textField == self.chooseAuthNoneNum) {
        [self.chooseAuthNoneNum showAuthChoose];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==self.chooseAuth || textField == self.chooseAuthNoneNum) {
        return NO;
    }
    return TRUE;
}


- (void)changeLanguage {
}
#pragma mark 风险采集调用
//风险采集调用获得
-(void) doJAQVerfificationToken
{
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             id<IOpenSecurityBodyComponent> sbComp = [[OpenSecurityGuardManager getInstance] getSecurityBodyComp];
             NSError* error = nil;
             NSString* wtoken = [sbComp getSecurityBodyDataEx: nil
                                                        appKey: nil
                                                      authCode: @"0335"
                                                   extendParam: nil
                                                          flag: OPEN_SECURITYBODY_FLAG_FORMAT_GENERAL //指定格式
                                                           env: OPEN_SECURITYBODY_ENV_ONLINE //指定环境
                                                         error: &error];
             NSLog(@"dojaqverX=%@",wtoken);
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self tokenQueryFinished:nil wtoken:wtoken];
             });

         });
     
}


- (void)pushAuthVC:(MSAuthType)type{
    self.status.text = @"";
   [self doJAQVerfificationToken];
}

//当接入服务端用一下用户访问,
//邮箱 test_hua@test.com
//test_phone@test.com
//test_sms@test.com
//test_shake@test.com
//test_gun@test.com
//会跳出对应的验证方式
#pragma mark 风险识别
//将wtoken利用三方服务器,透传到聚安全服务器
-(void)tokenQueryFinished:(NSError *)error wtoken:(NSString *)tokenid
{
    NSString* formaturl = @"http://%@:8080/action/wtoken=%@&&mail=%@&&phone=%@";
    [[NSUserDefaults standardUserDefaults] setValue:self.ipaddress.text forKey:@"ip"];
/**************************************************************************************************************/
#pragma mark 账号和电话应该在服务器端设置而不是客户端,增加这些只是为了demo更快看到效果避免修改后端代码
/*****账号和电话应该在服务器端设置而不是客户端,增加这些只是为了demo更快看到效果避免修改后端代码**************************/
    NSString* mail = @"";
    switch (self->mAuthType) {
        case MSAuthTypeSms:
            mail = @"test_sms@test.com";
            break;
        case MSAuthTypeCall:
            mail = @"test_phone@test.com";
            break;
    
        case MSAuthTypeSlide:
            mail = @"test_hua@test.com";
            break;
        case MSAuthBallShake:
            mail = @"test_shake@test.com";
            break;
        case MSAuthBallRoll:
            mail = @"test_gun@test.com";
            break;
        default:
            break;
    }
    self.host = self.ipaddress.text;

    NSString* url = [NSString stringWithFormat:formaturl,self.host,tokenid,mail,self.phonetext];
/**************************************************************************************************************/
    NSURLRequest* request = [NSURLRequest requestWithURL: [NSURL URLWithString:url]];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
}
#pragma mark 网络操作回调
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.status.text = error.localizedDescription;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)jsondata
{
   BOOL isToken = [connection.currentRequest.URL.path hasPrefix:@"/action/wtoken"];
    if (isToken) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingMutableLeaves error:nil];
        MSAuthType type = [dict[@"captcha_type"] integerValue];
        [self onAuthType:type data:dict[@"captcha_client_need_info"]];
        return;
    }
    else{
        NSString* jsonString = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
        //self.status.text = jsonString;
        [self.status setText:[NSString stringWithFormat:@"%@ %@", self.status.text, jsonString]];
    }
   
}
#pragma mark 风险验证
-(void)onAuthType:(MSAuthType)type data:(NSString*)data
{

    if (data==nil) {
        
        UIViewController *vc = [MSAuthVCFactory simapleVerifyWithType:type
                                                    language:@"en"
                                                  Delegate:self
                                                authCode:@"0335"
                                                  appKey:nil];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    UIViewController *vc = [MSAuthVCFactory  vcWithAuthType:type
                                                   jsonData:data
                                                   language:@"en"
                                                   Delegate:self
                                                   authCode:@"0335"
                                                     appKey:nil];

    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark 风险验证结果回传服务器
- (void)secondVerifyWithSessionId:(NSString *)sessionId
{
    if (sessionId) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSLog(@"SessionID = %@",sessionId);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString* formaturl = @"http://%@:8080/action/sessionid=%@";
                [[NSUserDefaults standardUserDefaults] setValue:self.ipaddress.text forKey:@"ip"];
                self.host = self.ipaddress.text;
                NSString* url = [NSString stringWithFormat:formaturl,self.host, sessionId];
                
                NSURLRequest* request = [NSURLRequest requestWithURL: [NSURL URLWithString:url]];
                [[NSURLConnection connectionWithRequest:request delegate:self] start];
            });
            
        });
    }
    else
    {
        NSLog(@"Error: SessionID is nil");
    }
}

#pragma mark 风险验证回调
- (void)verifyDidFinishedWithResult:(t_verify_reuslt)code Error:(NSError *)error SessionId:(NSString *)sessionId  {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error) {
            self.status.text = error.localizedDescription;
            NSLog(@"Error: %@", error);
        } else {
            NSString* msg = [NSString stringWithFormat:@"Authentication passed! Session id: %@", sessionId];
            self.status.text = msg;
            NSLog(@"%@",msg);
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        if (sessionId) {
            [self secondVerifyWithSessionId:sessionId];
        }
        
    });
}
@end

FAQ

关于此文档暂时还没有FAQ
返回
顶部