美文网首页
Flutter平台与iOS平台方法交互

Flutter平台与iOS平台方法交互

作者: z夜流星 | 来源:发表于2022-12-01 15:39 被阅读0次

    一:我们先来看看flutter应用的启动流程

    flutter应用的启动流程

    在流程图里我们看到,应用启动先执行ios原生平台的main函数,之后才会执行flutter平台的main函数
    ios应用启动后,会在ios原生平台的main()函数的代理方法里创建一个 FlutterViewController,并将 window的根页面设置为 FlutterViewController。这个FlutterViewController会隐式的创建一个FlutterEngine(flutter引擎)
    flutter引擎实例对象一旦运行,就会执行 flutter中的main()函数

    注意:在ios平台,我们写代码时要尽量保持FlutterEngine的复用,保证只有一个FlutterEngine对象,因为多个flutter引擎会导致fluttermain()方法执行多次;
    而我们知道主函数main()都是在整个应用程序生命周期中只执行一次的,主函数执行多次会导致不可预知的逻辑错误。

    二:flutter主动调用ios方法,ios方法被动响应。

    1:首先:我们需要在ios应用启动的代理方法- (void)applicationDidFinishLaunching:(UIApplication *)application里注册对flutter平台的监听:
    - (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      [GeneratedPluginRegistrant registerWithRegistry:self];
         
        //第一步:初始化ios调用flutter,用于ios平台主动调用flutter方法
        [[FlutterEvent sharedInstance] setUp];
         
        //第二步:初始化flutter调用ios,用于监听flutter传递过来的消息
        [[FlutterMethod sharedInstance] setUp];
         
      return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    
    FlutterMethod.m 文件中, setUp()方法的实现
    #import "FlutterMethod.h"
    #import "FlutterMethodKey.h"
    #import <Flutter/Flutter.h>
    #import "AppDelegate.h"
    
    // 通讯key
    #define Key_deliver_methodChannel @"com.deliver.method"
    
    /** 注册远程推送 */
     #define Key_RegisterRemotePush  @"register_remote_push";
    /** 获取App信息 */ 
    #define Key_GetAppInfo  @"get_appInfo";
    
    @implementation FlutterMethod
     
    static FlutterMethod* singleInstance = nil;
     
    + (instancetype)allocWithZone:(struct _NSZone *)zone {
         
        if(nil == singleInstance) {
            singleInstance = [super allocWithZone:zone];
        }
         
        return singleInstance;
    }
     
    + (FlutterMethod *)sharedInstance {
         
        if(nil == singleInstance) {
            singleInstance = [[FlutterMethod alloc] init];
        }
         
        return singleInstance;
    }
     
    - (void)setUp {
        //直接获取根页面FlutterViewController;再获取到FlutterEngine。
        FlutterViewController* flutterVC = (FlutterViewController*) [UIApplication sharedApplication].delegate.window.rootViewController;
        id binarymessenger = flutterVC.engine.binaryMessenger;
        FlutterMethodChannel* methodChannel = [FlutterMethodChannel methodChannelWithName:Key_deliver_methodChannel binaryMessenger:binarymessenger];
        __weak typeof(self) weakSelf = self;
        [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
             
            NSLog(@"flutter传给ios的参数:%@",call.arguments);
             
            if([Key_RegisterRemotePush isEqualToString:call.method]) {
                //开始注册推送...
                [AppDelegate beginRegisterRemotePush];
                result(nil);
            }else if([Key_GetAppInfo isEqualToString:call.method]) {
                //获取应用信息
                NSString* appInfo = [weakSelf getAppInfo];
                result(appInfo);
            }
        }];
    }
     
    end
    
    2:然后,在flutter平台需要调用ios原生方法时可以这样写:
    void registerRemotePush() async {
     
      if(Platform.isIOS) {
        //注册推送功能,ios使用原生平台推送
        dynamic response = await FlutterMethodChannel.flutterCallNativeMethod(FlutterMethodKey.Key_RegisterRemotePush, {"data":"传点什么参数好呢???"});
        print("ios回传的参数:$response");
      }else if(Platform.isAndroid) {
    
      }
    }
    
    FlutterMethodChannel类的封装:
    import 'dart:convert';
    import 'package:flutter/services.dart';
     
    /**
     * flutter 主动调用原生平台方法
     * */
     
    class FlutterMethodKey {
     
      /// flutter调用(ios/android)方法,一个Key对应一个方法。
     
      static const Key_RegisterRemotePush = "register_remote_push";/** 注册远程推送 */
      static const Key_GetAppInfo  = "get_appInfo";/** 获取App信息 */
    }
     
    class FlutterMethodChannel {
     
      static const _Key_MethodChannel = "com.deliver.method";
      static const _platform = const MethodChannel(_Key_MethodChannel);
     
      // flutter调用原生
      static Future<dynamic> flutterCallNativeMethod(String methodKey, dynamic params) async {
     
        if(null==params){params = "";}
        print('flutter调用原生:$methodKey');
        print('flutter传给原生参数:$params');
     
        try {
          var result = await _platform.invokeMethod(methodKey,params);
          return result;
        }on PlatformException catch (e) {
          print("flutter调用原生平台方法出错:${e.message}");
          return e;
        }
      }
    }
    

    三: ios主动调用flutter方法,flutter被动响应

    1:首先:我们需要在 flutter应用启动的 main.dart文件里注册对ios原生平台的监听:
    void main() {
      runApp(MyApp());
    }
     
    class MyApp extends StatefulWidget {
      @override
      MyAppState createState() => MyAppState();
    }
     
    class MyAppState extends State<MyApp> {
     
      @override
      void initState() {
        super.initState();
        //注册原生调用flutter的监听
        FlutterEventChannel.registerEventChannel();
      }
    }
    
    FlutterEventChannel类的封装:
    import 'dart:convert';
    import 'package:flutter/services.dart';
    
    /**
     * 原生平台方法调用 flutter 都会触发这里的回调。
     * */
     
    class FlutterEventKey {
     
      ///(ios/android)调用flutter方法,一个Key对应一个方法。
     
      static const Key_ReceivePushToken = "receive_push_token";/** 获取到了推送token */
     
    }
     
    class FlutterEventChannel {
     
      static const _Key_EventChannel = "com.deliver.event";
      static const EventChannel _eventChannel = const EventChannel(_Key_EventChannel);
     
      ///注册(ios/android)调用flutter的事件回调
      static void registerEventChannel() {
         _eventChannel.receiveBroadcastStream().listen(
           _onNativeCallFlutterEvent,
           onError: _onNativeCallFlutterError,
         );
       }
     
       ///如果原生平台调用 flutter,下面的这个方法就会被触发执行。
       static void _onNativeCallFlutterEvent(dynamic event) {
        print("native平台给flutter传参数啦:$event");
        if(event is String) {
          var eventObject = json.decode(event);
          if(eventObject is Map) {
            var    data = eventObject["data"];
            String method = eventObject["method"];
     
            if(method == FlutterEventKey.Key_ReceivePushToken) {
              _savePushTokenToLocalDevice(data);
            }
          }
        }
     
       }
     
       ///如果调用 flutter 出错了,下面的这个方法就会执行。
       static void _onNativeCallFlutterError(Object error) {
     
       }
     
       //*****  10101010101010101010101010101010101010101010101010101010101010101010101010101010  *****//
     
      static void _savePushTokenToLocalDevice(String pushToken) {
        //将获取到的推送token保存到本地
       // save()...
    
      }
    }
    
    2:然后、在ios需要调用flutter的时候,我们可以这么写:
     #define  Key_ReceivePushToken @''receive_push_token" // 和flutter端 保持一致。
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        //获取token
        NSString *token=@"获取token"
        NSLog(@"苹果apns推送获取token成功:%@",token);
        [[FlutterEvent sharedInstance] platformCallFlutter:Key_ReceivePushToken data:token];
    }
    
    FlutterEvent.m文件中, - (void)platformCallFlutter:(NSString*)methodKey data:(NSObject*)value方法的实现
    #import "FlutterEvent.h"
    #import <Flutter/Flutter.h>
    #define Key_deliver_eventChannel @"com.deliver.event"
     
    @interface FlutterEvent()<FlutterStreamHandler>
    @property(nonatomic,strong)FlutterEventSink eventSink;;
    @end
     
    @implementation FlutterEvent
     
    static FlutterEvent* singleInstance = nil;
     
    + (instancetype)allocWithZone:(struct _NSZone *)zone {
         
        if(nil == singleInstance) {
            singleInstance = [super allocWithZone:zone];
        }
         
        return singleInstance;
    }
     
    + (FlutterEvent *)sharedInstance {
         
        if(nil == singleInstance) {
            singleInstance = [[FlutterEvent alloc] init];
        }
         
        return singleInstance;
    }
     
    - (void)setUp {
         
        FlutterViewController* flutterVC = (FlutterViewController*) [UIApplication sharedApplication].delegate.window.rootViewController;
        id binarymessenger = flutterVC.engine.binaryMessenger;
        FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:Key_deliver_eventChannel binaryMessenger:(NSObject<FlutterBinaryMessenger> *)binarymessenger];
        [eventChannel setStreamHandler:self];
    }
     
    - (void)platformCallFlutter:(NSString *)methodKey data:(NSObject *)value {
         
        if(nil == methodKey) {
            return;
        }
         
        NSDictionary* dataDic = @{@"method":methodKey,@"data":value};
        NSData* data = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString* jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         
        if(self.eventSink) {
            self.eventSink(jsonStr);
        }
    }
     
    #pragma mark - FlutterStreamHandler
    - (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
        self.eventSink = events;
        return nil;
    }
     
    - (FlutterError *)onCancelWithArguments:(id)arguments {
        NSLog(@"flutter给ios的参数(arguments):%@",arguments);
        return nil;
    }
     
    @end
    

    四:总结

    1:flutter调用ios,使用 MethodChannel类的 invokeMethod()
    2:ios调用flutter,使用 EventChannel 类的 receiveBroadcastStream()
    flutter与iOS通讯流程

    相关文章

      网友评论

          本文标题:Flutter平台与iOS平台方法交互

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