uniapp 开发实四 :uniapp 与ios原生交互

效果如下图:

uniapp:代码

<template>
      
    <view class="contain">
        <input type="number" v-model="num1" @input="onKeyInput1" class="numstyle" placeholder="请输入加数1" />
        <text style="margin-left: 15rpx;margin-right: 15rpx;">+</text>
        <input type="number" v-model="num2"  @input="onKeyInput2" class="numstyle" placeholder="请输入加数2" />
         <button type="primary" style="width: 80rpx;height: 80rpx;" @click="testFunc">=</button>
        <input type="number" v-model="num3" class="numstyle"/>
    </view>
     
        
</template>

<script>
    // 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module 
    var nativeModule = uni.requireNativePlugin("DCTestUniPlugin-NatvieModule")
    export default {
        data() {  
            return {  
                num1: "",  
                num2: "",
                num3:""
            };  
        },  
        methods: {
             onKeyInput1: function(event) {  
                this.num1 = event.target.value  
            },
            onKeyInput2: function(event) {
                this.num2 = event.target.value  
            },
            testFunc() {
                
                // 调用异步方法
                nativeModule.testFunc({
                        'num1': this.num1,
                        'num2': this.num2
                    },
                    (ret) => {
                        this.num3=ret;
                    })
            }
        }
    }
            
</script>
<style>
    .contain{
       
        display: flex;
        flex-direction: row;
        align-items: center;
        height: 80rpx;
    }   
    .numstyle{
        width: 180rpx;
        height: 80rpx;
        text-align: center;
        background-color: #4CD964;
    }
    
</style>

ios原生代码:

@implementation NatvieModule

// 通过宏 UNI_EXPORT_METHOD 将异步方法暴露给 js 端

UNI_EXPORT_METHOD(@selector(testFunc:callback:))

/// 异步方法(注:异步方法会在主线程(UI线程)执行)

/// @param options js 端调用方法时传递的参数

/// @param callback 回调方法,回传参数给 js 端

- (void)testFunc:(NSDictionary *)options callback:(UniModuleKeepAliveCallback)callback {

    // options 为 js 端调用此方法时传递的参数

    NSLog(@"%@",options);

    double  num1=[[options objectForKey:@"num1"] doubleValue];

    double  num2=[[options objectForKey:@"num2"] doubleValue];

    

    // 可以在该方法中实现原生能力,然后通过 callback 回调到 js

    double  num3=num1+num2;

    NSLog(@"1111%f",num3);

    // 回调方法,传递参数给 js 端 注:只支持返回 String 或 NSDictionary (map) 类型

    if (callback && num3) {

        NSLog(@"11112222");

        // 第一个参数为回传给js端的数据,第二个参数为标识,表示该回调方法是否支持多次调用,如果原生端需要多次回调js端则第二个参数传 YES;

        callback([NSString stringWithFormat:@"%.2lf" ,num3],NO);

    }

}

@end

猜你喜欢

转载自blog.csdn.net/qq_40263927/article/details/122765826
今日推荐