React Native调用IOS原生继承NSObject的控件方法

下面是iOS原生控件的相关代码,也同时调用原生,查看相关权限,如相册,相机,定位,通知状态等权限

#import 
#import 
#import 

NS_ASSUME_NONNULL_BEGIN

@interface PermissionsManager : NSObject

@end

NS_ASSUME_NONNULL_END
//
//  PermissionsManager.m
//  TempApp
//
//  Created by jiangguoxing-mac on 2019/11/5.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "PermissionsManager.h"
#import 
#import 
#import 
#import 

//iOS调用RN
#import 

@implementation PermissionsManager

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

- (NSDictionary *)baseInfomation {
  return @{ @"name": @"PermissionsManager" };
}

//Promises
//最后两个参数是RCTPromiseResolveBlock(成功block)和RCTPromiseRejectBlock(失败block)

/*
 //正确回调,传递参数
 
 typedef void (^RCTPromiseResolveBlock)(id result);
 
 */

/*
 //错误回调,传三个参数
 
 typedef void (^RCTPromiseRejectBlock)(NSString *code, NSString *message, NSError *error);
 
 */


#define IOS8 ([[[UIDevice currentDevice] systemVersion] doubleValue] >=8.0 ? YES : NO)
/**
 相机权限
 
 */
RCT_EXPORT_METHOD(cameraPermission:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
  
  AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  
  if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied){
    //无权限
    reject(@"500",@"没有访问相机权限,请前往 ‘设置’-‘隐私’-‘相机’ 开启权限",nil);
  }else if (authStatus == AVAuthorizationStatusNotDetermined ){
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
      
      dispatch_async(dispatch_get_main_queue(), ^{
        
        if (granted) {
          //允许访问
          if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {
            //模拟器
            reject(@"500",@"模拟器无法访问摄像头,请换真机",nil);
          }else{
            //真机
            resolve(@YES);
          }
        }else{
          //不允许访问
          reject(@"500",@"没有访问相机权限,请前往 ‘设置’-‘隐私’-‘相机’ 开启权限",nil);
        }
      });
      
    }];
    
  }else{
    if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {
      //模拟器
      reject(@"500",@"模拟器无法访问摄像头,请换真机",nil);
    }else{
      //真机
      resolve(@YES);
    }
  }
}

/**
 相册权限
 
 */
RCT_EXPORT_METHOD(photoPermission:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
  
  
  if (IOS8) { //iOS9以上包含iOS9
    
    PHAuthorizationStatus phStatus =  [PHPhotoLibrary authorizationStatus];
    
    if (phStatus == PHAuthorizationStatusNotDetermined) {
      [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        if (status == PHAuthorizationStatusAuthorized) {
          //允许访问
          resolve(@YES);
        }
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
          //不允许
          reject(@"500",@"没有访问相册权限,请前往 ‘设置’-‘隐私’-‘相册’ 开启权限",nil);
        }
      }];
    }else if (phStatus == PHAuthorizationStatusRestricted || phStatus == PHAuthorizationStatusDenied){
      reject(@"500",@"没有访问相册权限,请前往 ‘设置’-‘隐私’-‘相册’ 开启权限",nil);
    }else{
      resolve(@YES);
    }
    
  }else{ // ios7 以下
    
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied)
    {
      //无权限
      reject(@"500",@"没有访问相册权限,请前往 ‘设置’-‘隐私’-‘相册’ 开启权限",nil);
      
    }else {
      // 有权限
      resolve(@YES);
      
    }
  }
}

/**
 定位权限
 
 */
RCT_EXPORT_METHOD(locationPermission:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
  
  if([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
    //无权限
    reject(@"500",@"没有访问位置权限,请前往 ‘设置’-‘隐私’-‘位置’ 开启权限",nil);
    
  }else {
    // 有权限
    
    resolve(@YES);
    
  }
}

/**
 麦克风权限
 
 */
RCT_EXPORT_METHOD(microphonePermission:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) {
  
  AVAudioSession *avSession = [AVAudioSession sharedInstance];
  
  if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
    
    [avSession requestRecordPermission:^(BOOL available) {
      if (available) {
        resolve(@YES);
      }else {
        reject(@"500",@"没有访问麦克风权限,请前往 ‘设置’-‘隐私’-‘麦克风’ 开启权限",nil);
      }
    }];
    
  }
}

/**
 通知状态
 
 */

RCT_EXPORT_METHOD(notificationStatus:(RCTResponseSenderBlock)callback){
  
  if (IOS8) { //iOS8以上包含iOS8
    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types  == UIUserNotificationTypeNone) {
      callback(@[@NO]);
    }else{
      callback(@[@YES]);
    }
  }else{ // ios7 以下
    if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes]  == UIRemoteNotificationTypeNone) {
      callback(@[@NO]);
    }else{
      callback(@[@YES]);
    }
  }
  
}
@end

其中RCT_EXPORT_METHOD()是导出方法名

下面是RN调用原生的方法,这是我封装的一个RN类,与调用原生的方法

import React, { Component } from 'react';
import {
    View,
    NativeModules,
    NativeAppEventEmitter,//导入
} from 'react-native';


//在JavaScript中调用Object-C定义的方法,需要先导入NativeModules
//此处的RNCalliOSAction就是我们在iOS上新建的类名
//如果在iOS中设置了导出了类的名字,此处需要和导出的名字一致
const manager = NativeModules.PermissionsManager;

/*相机权限*/
const cameraPermission = () => {

   return new Promise((resolve, reject) => {
       manager.cameraPermission().then(data => {
           resolve(data);
       }).catch(err => {
           reject(err);
       });
   });
};

/*相机权限*/
const photoPermission = () => {

    return new Promise((resolve, reject) => {
        manager.photoPermission().then(data => {
            resolve(data);
        }).catch(err => {
            reject(err);
        });
    });
};

/*位置权限*/
const locationPermission = () => {

    return new Promise((resolve, reject) => {
        manager.locationPermission().then(data => {
            resolve(data);
        }).catch(err => {
            reject(err);
        });
    });
};

/*麦克风权限*/
const microphonePermission = () => {

    return new Promise((resolve, reject) => {
        manager.microphonePermission().then(data => {
            resolve(data);
        }).catch(err => {
            reject(err);
        });
    });
};

/*通知状态*/
const notificationStatus = () => {

    return new Promise((resolve) => {
        manager.notificationStatus((status)=>{
            resolve(status);
        });
    });
};

/*通知状态*/
const getLocalAssets = () => {

    return new Promise((resolve, reject) => {
        manager.getLocalBundle().then(data => {
            resolve(data);
        }).catch(err => {
            reject(err);
        });
    });
};
export default {
    cameraPermission,
    photoPermission,
    locationPermission,
    microphonePermission,
    notificationStatus,
    getLocalAssets
};

下面是在RN相关页面中的使用方法

import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Platform } from 'react-native';
//首先要导入自己定义的文件
import PermissionsManager from '../../commons/utils/permissionsManager';

export default class WriteTaskForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
        }
    }

    render() {

        return (
            
                 { this.method()}}>
                      实例
                
            
        )
    }

    // 回调
    method() {
        PermissionsManager.cameraPermission().then(data => {
             //成功的返回
         }).catch(err => {
             //失败的返回
             alert(err.message);
         });
    }
}

const styles = {
    container: {
        flex: 1,
        backgroundColor: '#9a9a9a'
    },
}

你可能感兴趣的:(React Native调用IOS原生继承NSObject的控件方法)