Flutter开发圈Flutter

flutter 调用iOS原声

2020-06-08  本文已影响0人  Faith_K

flutter 与iOS交互通道是MethodChannel 方法

1.flutter代码实现

  Future runiOSMethod() async {
  //通道名称 
    const platform = const MethodChannel('laitong');
    var result;
    try {
      //方法跟参数
      result = await platform.invokeMethod('iosPay',{'payId':''});
      return Future.value(result);
    } on PlatformException catch (e) {
      return Future.error(e.toString());
    }
  }
  1. 新建 iOS 文件,右键选择ios目录用xcode打开


    image.png

    右击新建文件 ,继承与NSObject


    image.png

.h

#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>

NS_ASSUME_NONNULL_BEGIN

@interface FlutterIosPay : NSObject<FlutterPlugin>
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar;
@end

NS_ASSUME_NONNULL_END

.m

//
//  FlutterIosPay.m
//  Runner
//
//  Created by faith on 2020/6/4.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "FlutterIosPay.h"
#import "InPurchasingManager.h"
@implementation FlutterIosPay
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"laitong" binaryMessenger:[registrar messenger]];
    FlutterIosPay *instance = [[FlutterIosPay alloc]init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([call.method isEqualToString:@"iosPay"]) {
        //接受fultter 传过来的参数
        NSLog(@"---%@",call.arguments);
       result(@"返回给fullter的");
    }else {
        result(FlutterMethodNotImplemented);
    }
}


@end

3.在AppDelegate.swift 注册

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    FlutterIosPay.register(with: self.registrar(forPlugin: "FlutterIosPay"));
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

如果创建的是oc 文件需要在桥接文件Runner-Bridging-Header里面 引入

image.png

4.在flutter 中调用 我们刚才写的方法 runiOSMethod

      var futureValue = await runiOSMethod();
          print(futureValue);

image.png
上一篇下一篇

猜你喜欢

热点阅读