美文网首页
iOS OC和JS交互

iOS OC和JS交互

作者: RogueYBJ | 来源:发表于2019-06-19 10:36 被阅读0次

    这里我就不多解释了
    项目里的东西全放进来了
    东西较多
    请看完后自行更改
    .h文件

    
    #import <UIKit/UIKit.h>
    
    #define JSPath @"documentView.webView.mainFrame.javaScriptContext"
    
    #import <JavaScriptCore/JavaScriptCore.h>
    
    #import <ContactsUI/ContactsUI.h>
    
    @protocol JSProtocol <JSExport>
    
    //人脸识别
    -(void)face;
    
    //身份证正面
    -(void)idpositive;
    
    //身份证反面
    -(void)idback;
    
    //客服
    -(void)goKefu:(NSString *)UserId UserDic:(NSDictionary *)UserDic;
    
    //获取通讯录
    -(void)contactsAll;
    
    //手机信息
    -(void)phoneTest;
    
    @end
    
    @interface ViewController : UIViewController
    
    
    @end
    

    .m文件

    
    #import "ViewController.h"
    
    //人脸识别
    #import "STLivenessController.h"
    
    #import "STLivenessDetector.h"
    
    #import "LivingSettingGLobalData.h"
    
    #import "STLivenessCommon.h"
    
    //身份证识别
    #import "STIdCardScanner.h"
    
    #import "ResultViewController.h"
    
    #import "UIView+STLayout.h"
    
    NSTimeInterval const kTimeoutSeconds = 15;
    
    //美恰客服
    #import <MQChatViewStyle.h>
    
    #import <MQChatViewManager.h>
    
    @interface ViewController ()<CAAnimationDelegate,UIWebViewDelegate ,JSProtocol,STLivenessDetectorDelegate,STLivenessControllerDelegate,STIdCardScannerDelegate,STCardScannerControllerDelegate,CNContactPickerDelegate>
    
    @property(weak ,nonatomic)UIWebView * web;
    
    /**
     活体检测
     */
    @property (weak, nonatomic) STLivenessController *livenessVC;
    
    /**
     身份证识别
     */
    
    @property (nonatomic, strong)UILabel *lbError;
    @property (nonatomic, strong)UILabel *lbVersion;
    @property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
    @property (strong, nonatomic) NSTimer *timer;
    @property (nonatomic, strong) STIdCardScanner *scanIdCardVC;
    @property (nonatomic, assign) RecogResultType type;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.view.backgroundColor = [UIColor whiteColor];
        
        UIWebView * webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
        
        _web = webView;
        
        webView.scrollView.bounces = NO;
        
        webView.delegate = self;
        
        [self.view addSubview:webView];
        
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
    }
    
    -(void)webViewDidFinishLoad:(UIWebView *)webView
    {
        JSContext *context = [webView valueForKeyPath:JSPath];
        context[@"js"] = self;
    }
    
    #pragma mark - js->OC js调用OC
    
    -(void)face{
        
        NSLog(@"人脸识别");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self LiveTesting];
        });
    }
    -(void)idpositive{
        NSLog(@"身份证正面");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self CardPositiveIdentify];
        });
    }
    
    -(void)idback{
        NSLog(@"身份证反面");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self CardReverseIdentify];
        });
    }
    
    
    
    -(void)goKefu:(NSString *)UserId UserDic:(NSDictionary *)UserDic{
        NSLog(@"客服");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self MQkefuUserIdStr:UserId andUserList:UserDic];
        });
    }
    
    -(void)contactsAll{
        NSLog(@"获取通讯录");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self requestContactAuthorAfterSystemVersion9];
        });
    }
    
    -(void)phoneTest{
        NSLog(@"手机信息");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self phoneInformation];
        });
    }
    
    /**
     活体检测==============================================
     */
    
    -(void)LiveTesting{
        [LivingSettingGLobalData sharedInstanceData].strSequence = @"BLINK MOUTH";
        [LivingSettingGLobalData sharedInstanceData].liveComplexity = LIVE_COMPLEXITY_NORMAL;
        [LivingSettingGLobalData sharedInstanceData].bVoicePrompt = YES;
        NSArray *arrStrSequence =
        [[LivingSettingGLobalData sharedInstanceData].strSequence componentsSeparatedByString:@" "];
        NSMutableArray *arrLivenessSequence = [NSMutableArray array];
        for (NSString *strAction in arrStrSequence) {
            if ([strAction isEqualToString:@"BLINK"]) {
                [arrLivenessSequence addObject:@(LIVE_BLINK)];
            } else if ([strAction isEqualToString:@"MOUTH"]) {
                [arrLivenessSequence addObject:@(LIVE_MOUTH)];
            } else if ([strAction isEqualToString:@"NOD"]) {
                [arrLivenessSequence addObject:@(LIVE_NOD)];
            } else if ([strAction isEqualToString:@"YAW"]) {
                [arrLivenessSequence addObject:@(LIVE_YAW)];
            } else {
                //            [self AlertViewMothods:@"动作序列设置有误"];
                return;
            }
        }
        
        STLivenessController *livenessVC = [[STLivenessController alloc] initWithApiKey:ACCOUNT_API_KEY
                                                                              apiSecret:ACCOUNT_API_SECRET
                                                                            setDelegate:self
                                                                      detectionSequence:arrLivenessSequence];
        //设置每个模块的超时时间
        [livenessVC.detector setTimeOutDuration:kDefaultTimeOutDuration];
        
        // 设置活体检测复杂度
        [livenessVC.detector setComplexity:[LivingSettingGLobalData sharedInstanceData].liveComplexity];
        
        // 设置活体检测的阈值
        [livenessVC.detector setHacknessThresholdScore:kDefaultHacknessThresholdScore];
        
        // 设置是否进行眉毛遮挡的检测,如不设置默认为不检测
        livenessVC.detector.isBrowOcclusion = NO;
        
        //     设置默认语音提示状态,如不设置默认为开启
        livenessVC.isVoicePrompt = [LivingSettingGLobalData sharedInstanceData].bVoicePrompt;
        self.livenessVC = livenessVC;
        
        [self presentViewController:self.livenessVC animated:YES completion:nil];
        
        
    }
    
    
    #pragma mark -- STLivenessDetectorDelegate
    
    /**
     *  活体检测成功回调
     *
     *  @param protobufId         回传加密后的二进制数据在公有云的id
     *  @param protobufData       回传加密后的二进制数据
     *  @param requestId          网络请求的id
     *  @param imageArr           根据指定输出方案回传 STImage 数组 , STImage属性见 STImage.h
     */
    
    - (void)livenessDidSuccessfulGetProtobufId:(NSString *)protobufId
                                  protobufData:(NSData *)protobufData
                                     requestId:(NSString *)requestId
                                        images:(NSArray *)imageArr{
        // 取出每个阶段的图片
        NSMutableArray *resultImageArr = [NSMutableArray array];
        
        for (STImage *image in imageArr) {
            
            [resultImageArr addObject:image.image];
            
        }
        
        [self callJs:@"userFaceImg" parameter:[self baseImage:resultImageArr[0]]];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    /**
     *  活体检测失败回调
     *
     *  @param errorType         失败的类型
     *  @param protobufData      回传加密后的二进制数据
     *  @param requestId         网络请求的id
     *  @param imageArr          根据指定输出方案回传 STImage 数组 , STImage属性见 STImage.h
     */
    
    - (void)livenessDidFailWithErrorType:(LivefaceErrorType)errorType
                            protobufData:(NSData *)protobufData
                               requestId:(NSString *)requestId
                                  images:(NSArray *)imageArr{
        NSString * str = @"";
        switch (errorType) {
            case STIDLiveness_E_LICENSE_INVALID: {
                str = @"未通过授权验证";
                break;
            }
            case STIDLiveness_E_LICENSE_FILE_NOT_FOUND: {
                str = @"授权文件不存在";
                break;
            }
            case STIDLiveness_E_LICENSE_BUNDLE_ID_INVALID: {
                str = @"绑定包名错误";
                break;
            }
            case STIDLiveness_E_LICENSE_EXPIRE: {
                str = @"授权文件过期";
                break;
            }
            case STIDLiveness_E_LICENSE_VERSION_MISMATCH: {
                str = @"License与SDK版本不匹";
                break;
            }
            case STIDLiveness_E_LICENSE_PLATFORM_NOT_SUPPORTED: {
                str = @"License不支持当前平台";
                break;
            }
            case STIDLiveness_E_MODEL_INVALID: {
                str = @"模型文件错误";
                break;
            }
            case STIDLiveness_E_MODEL_FILE_NOT_FOUND: {
                str = @"模型文件不存在";
                break;
            }
            case STIDLiveness_E_MODEL_EXPIRE: {
                str = @"模型文件过期";
                break;
            }
            case STIDLiveness_E_NOFACE_DETECTED: {
                str = @"动作幅度过⼤,请保持人脸在屏幕中央,重试⼀次";
                
                break;
            }
            case STIDLiveness_E_FACE_OCCLUSION: {
                str = @"请调整人脸姿态,去除面部遮挡,正对屏幕重试一次";
                
                break;
            }
            case STIDLiveness_E_TIMEOUT: {
                str = @"检测超时,请重试一次";
                break;
            }
            case STIDLiveness_E_INVALID_ARGUMENT: {
                str = @"参数设置不合法";
                break;
            }
            case STIDLiveness_E_CALL_API_IN_WRONG_STATE: {
                str = @"错误的方法状态调用";
                break;
            }
            case STIDLiveness_E_API_KEY_INVALID: {
                str = @"API_KEY或API_SECRET错误";
                break;
            }
            case STIDLiveness_E_SERVER_ACCESS: {
                str = @"服务器访问错误";
                break;
            }
            case STIDLiveness_E_SERVER_TIMEOUT: {
                str = @"网络连接超时,请查看网络设置,重试一次";
                break;
            }
            case STIDLiveness_E_HACK: {
                str = @"未通过活体检测";
                break;
            }
        }
        //弹框提示
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *_cancelAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:_cancelAction];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    /**
     *  活体检测被取消的回调
     */
    - (void)livenessDidCancel {
        //弹框提示
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"相机权限获取失败:请在设置-隐私-相机中开启后重试" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *_cancelAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:_cancelAction];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    #pragma mark -- STLivenessControllerDelegate
    
    - (void)livenessControllerDeveiceError:(STIdDeveiceError)deveiceError{
        //弹框提示
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"扫描失败,请重试!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *_cancelAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:_cancelAction];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    
    
    
    /**
     身份证识别==============================================
     */
    
    //正面
    -(void)CardPositiveIdentify{
        [self removeErrorMessage];
        self.lbError.hidden = YES;
        
        self.scanIdCardVC = [[STIdCardScanner alloc] initWithOrientation:AVCaptureVideoOrientationPortrait
                                                                  apiKey:ACCOUNT_API_KEY
                                                               apiSecret:ACCOUNT_API_SECRET
                                                                delegate:self];
        
        [self.scanIdCardVC.idCardRecognizer setTimeoutSeconds:kTimeoutSeconds];
        [self.scanIdCardVC.idCardRecognizer setImageMaxLossPrecentage:100];
        self.type = kResultTypeFront;
        [self.scanIdCardVC.idCardRecognizer setScanMode:STIdCardScanSingle
                                               scanSide:STIdCardScanFrontal
                                    recognizeItemOption:STIdCardItemAll];
        [self presentViewController:self.scanIdCardVC animated:NO completion:nil];
        [self.scanIdCardVC.view addSubview:self.activityIndicatorView];
    }
    
    //反面
    -(void)CardReverseIdentify{
        [self removeErrorMessage];
        self.lbError.hidden = YES;
        
        self.scanIdCardVC = [[STIdCardScanner alloc] initWithOrientation:AVCaptureVideoOrientationPortrait
                                                                  apiKey:ACCOUNT_API_KEY
                                                               apiSecret:ACCOUNT_API_SECRET
                                                                delegate:self];
        
        [self.scanIdCardVC.idCardRecognizer setTimeoutSeconds:kTimeoutSeconds];
        [self.scanIdCardVC.idCardRecognizer setImageMaxLossPrecentage:100];
        self.type = kResultTypeBack;
        [self.scanIdCardVC.idCardRecognizer setScanMode:STIdCardScanSingle
                                               scanSide:STIdCardScanBack
                                    recognizeItemOption:STIdCardItemAll];
        [self presentViewController:self.scanIdCardVC animated:NO completion:nil];
        [self.scanIdCardVC.view addSubview:self.activityIndicatorView];
    }
    
    //公共方法
    - (void)removeErrorMessage {
        self.lbError.hidden = YES;
        self.lbError.text = @"";
    }
    
    //公共方法
    - (void)timerInvalidate {
        if ([self.timer isValid]) {
            [self.timer invalidate];
        }
    }
    
     #pragma mark -- STIdCardScannerDelegate
    - (void)receivedIdCardResult:(STIdCard *)idCard requestId:(NSString *)requestId{
        [self removeErrorMessage];
        switch (self.type) {
            case kResultTypeFront: {
                [self parseIdCardFront:idCard];
            } break;
            case kResultTypeBack: {
                [self parseIdCardBack:idCard];
            } break;
            case kResultTypeNameAndNumOnly: {
                
            } break;
            case kResultTypeUICustom: {
                if (idCard.cardSide == STIdCardSideFront) {
                    [self parseIdCardFront:idCard];
                } else {
                    [self parseIdCardBack:idCard];
                }
            } break;
            case kResultTypeScanFrontAndBack: {
                [self parseIdCardFront:idCard];
                [self parseIdCardBack:idCard];
            } break;
            default:
                break;
        }
    }
    
    /**
     @method receivedBankCardError:
     
     @abstract  出现错误时的回调函数
     
     @param errorCode  不同错误的错误代码
     @param requestId 请求ID
     
     @discussion
     无请求 ID 时,requestID 为 @""
     */
    - (void)receivedIdCardError:(STOCRError)errorCode requestId:(NSString *)requestId{
        [_activityIndicatorView stopAnimating];
        [self timerInvalidate];
        [self dismissViewControllerAnimated:YES completion:nil];
        self.lbError.hidden = NO;
        self.scanIdCardVC = nil;
        switch (errorCode) {
            case STID_E_API_KEY_INVALID: {
                self.lbError.text = @"API账户信息错误,请检查API_KEY和API_SECRET";
            } break;
            case STID_E_LICENSE_FILE_NOT_FOUND: {
                self.lbError.text = @"授权文件不存在";
            } break;
            case STID_E_MODEL_FILE_NOT_FOUND: {
                self.lbError.text = @"模型文件不存在";
            } break;
            case STID_E_LICENSE_INVALID: {
                self.lbError.text = @"授权文件不合法";
            } break;
            case STID_E_LICENSE_BUNDLE_ID_INVALID: {
                self.lbError.text = @"绑定包名错误";
            } break;
            case STID_E_LICENSE_EXPIRE: {
                self.lbError.text = @"授权文件过期";
            } break;
            case STID_E_LICENSE_VERSION_MISMATCH: {
                self.lbError.text = @"授权文件与SDK版本不匹配";
                break;
            }
            case STID_E_LICENSE_PLATFORM_NOT_SUPPORTED: {
                self.lbError.text = @"授权文件不支持当前平台";
                break;
            }
            case STID_E_TIMEOUT: {
                self.lbError.text = @"扫描超时,请重试一次";
            } break;
            case STID_E_SERVER_ACCESS: {
                self.lbError.text = @"服务器访问错误";
            } break;
            case STID_E_MODEL_EXPIRE: {
                self.lbError.text = @"模型文件过期";
            } break;
            case STID_E_MODEL_INVALID: {
                self.lbError.text = @"模型文件格式错误";
            } break;
            case STID_E_SERVER_TIMEOUT: {
                self.lbError.text = @"网络连接超时,请稍后重试";
            } break;
            case STID_E_INVALID_ARGUMENT: {
                self.lbError.text = @"参数设置不合法";
            } break;
            default:
                break;
        }
    }
    
     #pragma mark -- STCardScannerControllerDelegate
    - (void)receiveDeveiceError:(STDeveiceError)deveiceError{
        [_activityIndicatorView stopAnimating];
        [self timerInvalidate];
        self.lbError.hidden = NO;
        switch (deveiceError) {
            case STCameraAuthorizationFailed: {
                self.lbError.text = @"相机授权失败,请在设置中打开相机权限";
            } break;
            case STCancelScan: {
                self.lbError.text = @"取消扫描";
            } break;
            default:
                break;
        }
        [self.scanIdCardVC.idCardRecognizer cancelIdCardRecognize];
        self.scanIdCardVC = nil;
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    //扫描正面成功
    - (void)parseIdCardFront:(STIdCard *)idcard {
        
        [self callJs:@"idCardProsImg" parameter:[NSString stringWithFormat:@"%@,'%@','%@',%@",[self baseImage:idcard.idCardFrontImage],idcard.idCardName,idcard.idCardId,[self baseImage:[self cropImage:idcard.idCardFrontImage atRect:idcard.rectPhotoImage]]]];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    //扫描反面成功
    - (void)parseIdCardBack:(STIdCard *)idcard{
        
        [self callJs:@"idCardConsImg" parameter:[self baseImage:idcard.idCardBackImage]];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
    /**
     美恰客服==============================================
     */
    #pragma mark  集成第五步: 跳转到聊天界面(button的点击方法)
    #pragma mark 总之, 要自定义UI层  请参考 MQChatViewStyle.h类中的相关的方法 ,要修改逻辑相关的 请参考MQChatViewManager.h中相关的方法
    #pragma mark  最简单的集成方法: 全部使用meiqia的,  不做任何自定义UI.
    
    -(void)MQkefuUserIdStr:(NSString *)userId andUserList:(NSDictionary *)UserDic{
        MQChatViewManager *chatViewManager = [[MQChatViewManager alloc] init];
        [chatViewManager setoutgoingDefaultAvatarImage:[UIImage imageNamed:@"meiqia-icon"]];
        
        #pragma mark 觉得头像 方形不好看 ,设置为圆形.
        MQChatViewStyle *aStyle = [chatViewManager chatViewStyle];
        //    dic == nil ? clientCustomizedAttrs :dic
        [aStyle setEnableRoundAvatar:YES];
        [chatViewManager setLoginCustomizedId:userId];
        
        [chatViewManager setClientInfo:UserDic override:YES];
        [aStyle setNavBarTintColor:[UIColor redColor]];
        [aStyle setNavBackButtonImage:[UIImage imageNamed:@"返回"]];
        
        [aStyle setNavBarColor:[UIColor whiteColor]];
        [aStyle setNavTitleColor:[UIColor blackColor]];
        //    [aStyle setNavBarBackgroundImage:[UIImage imageNamed:@"返回"]];
        //替换自定义TitleView
        
        [chatViewManager pushMQChatViewControllerInViewController:self];
    }
    
    
    /**
     获取通讯录
     */
    
    #pragma mark 请求通讯录权限
    - (void)requestContactAuthorAfterSystemVersion9{
        
        //让用户给权限,没有的话会被拒的各位
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusNotDetermined) {
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (error) {
                    NSLog(@"没有授权, 需要去设置中心设置授权");
                }else
                {
                    NSLog(@"用户已授权限");
                    //有通讯录权限-- 进行下一步操作
                    
                    CNContactPickerViewController * picker = [CNContactPickerViewController new];
                    picker.delegate = self;
                    // 加载手机号
                    picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
                    
                    [self presentViewController: picker  animated:YES completion:nil];
                }
            }];
        }
        
        if (status == CNAuthorizationStatusAuthorized) {
            [self openContact];
            //有权限时
            CNContactPickerViewController * picker = [CNContactPickerViewController new];
            picker.delegate = self;
            picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
            [self presentViewController: picker  animated:YES completion:nil];
        }
        else{
            NSLog(@"您未开启通讯录权限,请前往设置中心开启");
        }
        
    }
    
    //有通讯录权限-- 进行下一步操作
    - (void)openContact{
        // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
        NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        NSMutableArray * mArr = [NSMutableArray new];
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            //拼接姓名
            NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
            
            NSArray *phoneNumbers = contact.phoneNumbers;
            
            for (CNLabeledValue *labelValue in phoneNumbers) {
                //遍历一个人名下的多个电话号码
                CNPhoneNumber *phoneNumber = labelValue.value;
                NSString * string = phoneNumber.stringValue ;
                
                //去掉电话中的特殊字符
                string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
                string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
                
                NSDictionary * dic = @{
                                       @"phone":string,
                                       @"name":nameStr
                                       };
                
                
                
                [mArr addObject: dic];
            }
            
        }];
        
        /**
         数据请求
         */
    
        [self callJs:@"concatInfo" parameter:[NSString stringWithFormat:@"'data:image/png;base64,%@'",[[[[NSJSONSerialization dataWithJSONObject:mArr options:NSJSONWritingPrettyPrinted error:nil] base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] stringByReplacingOccurrencesOfString:@"\n"withString:@""] stringByReplacingOccurrencesOfString:@"\r" withString:@""]]];
    
    }
    
    - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
        
        CNContact *contact = contactProperty.contact;
        //获取姓名并且去除空格
        NSString * nameStr = [NSString stringWithFormat:@"%@%@",[contact.givenName stringByReplacingOccurrencesOfString:@" " withString:@""],[contact.familyName stringByReplacingOccurrencesOfString:@" " withString:@""]];
    
        CNPhoneNumber *phoneNumber = contactProperty.value;
        NSString * phoneStr = phoneNumber.stringValue;
    
        [self callJs:@"firstInfo" parameter:[NSString stringWithFormat:@"'%@','%@'",nameStr,phoneStr]];
    }
    
    /**
     手机型号
     */
    -(void)phoneInformation{
        
        //手机系统版本
        
        NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
        
        NSString* phoneModel = [[UIDevice currentDevice] model];
        
        [self callJs:@"phoneTest" parameter:[NSString stringWithFormat:@"'%@','%@'",phoneModel,phoneVersion]];
        
    }
    
    #pragma mark - OC->js
    
    //调用js
    -(void)callJs:(NSString *)funcName parameter:(NSString *)parameter{
        JSContext *contex = [self.web valueForKeyPath:JSPath];
    //    UIImage * image = [UIImage imageNamed:@"常见问题"];
    //    [formData appendPartWithFileData:UIImagePNGRepresentation(self.idCard2.idCardBackImage) name:@"file" fileName:@"backImg.jpg" mimeType:@"image/jpg"];
        [contex evaluateScript:[NSString stringWithFormat:@"%@(%@)",funcName,parameter]];
    }
    //图片转base
    -(NSString *)baseImage:(UIImage *)image{
    
        return [NSString stringWithFormat:@"'data:image/png;base64,%@'",[[[UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] stringByReplacingOccurrencesOfString:@"\n"withString:@""] stringByReplacingOccurrencesOfString:@"\r" withString:@""]];
    }
    
    //截取身份证人脸照片
    - (UIImage *)cropImage:(UIImage *)image atRect:(CGRect)rect {
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, image.size.width, image.size.height);
        CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));
        [image drawInRect:drawRect];
        UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return croppedImage;
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:iOS OC和JS交互

          本文链接:https://www.haomeiwen.com/subject/agdewqtx.html