美文网首页Flutter填坑手札iOS 技巧
Flutter Plugin 集成三方库开发教程

Flutter Plugin 集成三方库开发教程

作者: 践行丶见远 | 来源:发表于2019-08-27 16:51 被阅读0次

    刚好开发需求对接一个客服三方sdk 在此记录开发流程,并整理使用

    上传plugin需要翻墙!上传plugin需要翻墙!上传plugin需要翻墙!

    第一步

    -创建一个plugin
    flutter create --template=plugin 你希望的插件名称

    -如果有swift 或 kotlin 需求可添加
    flutter create --org com.loself --template=plugin -i swift -a kotlin 你希望的插件名称

    第二步

    -配置项目
    因为用的是第三方所以先导入第三方的sdk

    iOS配置找到路径根目录/ios/插件名.podspec
    Pod::Spec.new do |s|
      s.name             = 'meiqiachat'
      s.version          = '1.0.1'
      s.summary          = 'meiqia sdk init and to chat'
      s.description      = <<-DESC
    A new flutter plugin project. to use meiqian chat
                           DESC
      s.homepage         = 'http://example.com'
      s.license          = { :file => '../LICENSE' }
      s.author           = { 'loself' => 'loselfmin@gmail.com' }
      s.source           = { :path => '.' }
      s.source_files = 'Classes/**/*'
      s.public_header_files = 'Classes/**/*.h'
      s.dependency 'Flutter'
      s.dependency 'Meiqia', '~> 3.4.9'
      s.static_framework = true
      s.ios.deployment_target = '8.0'
    end
    

    s.dependency 'Meiqia', '~> 3.4.9'
    s.static_framework = true
    增加两项导入sdk
    设置用户信息s.author = { 'loself' => 'loselfmin@gmail.com' }

    android找到路径根目录/android/build.gradle

    在最下方添加

    dependencies {
        implementation 'com.meiqia:meiqiasdk:3.5.8'
        implementation 'com.android.support:support-v4:28.0.0'
        implementation 'com.squareup.okhttp3:okhttp:4.1.0'
        implementation 'com.github.bumptech.glide:glide:4.9.0'
        annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    }
    

    第三步

    找到根目录/lib/插件名称.dart
    创建flutter调用的方法,然后对应在ios和android中实现即可
    我这里只是简单调用客服所以只创建两个方法

      /// 初始化美洽sdk 
      static Future<void> initMeiqiaSdkWith(String appkey) async {
        await _channel.invokeMethod('initMeiqiaSdk', appkey);
      }
      /// 初始化聊天页面 isPush 为 iOS 跳转方式 默认present
      static Future<void> toChat({bool isPush}) async {
        await _channel.invokeMethod('toChat', isPush);
      }
    

    第四步iOS 和android实现交互调用

    此处直接贴代码,对应注意事项都有说明
    ios/Classes/插件名称.m

    #import "MeiqiachatPlugin.h"
    
    #import <MeiQiaSDK/MQManager.h>
    #import <MQChatViewManager.h>
    
    @implementation MeiqiachatPlugin
    
    + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
        FlutterMethodChannel* channel = [FlutterMethodChannel
                                         methodChannelWithName:@"meiqiachat"
                                         binaryMessenger:[registrar messenger]];
        MeiqiachatPlugin* instance = [[MeiqiachatPlugin alloc] init];
        // --- add applicationDelegate
        [registrar addApplicationDelegate:instance];
        [registrar addMethodCallDelegate:instance channel:channel];
    }
    
    - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
      if ([@"initMeiqiaSdk" isEqualToString:call.method]) {
        [self initSdk:call.arguments result:result];
      }else if ([@"toChat" isEqualToString:call.method]) {
        [self pushToMeiqiaVCWith:call.arguments];
      }else {
        result(FlutterMethodNotImplemented);
      }
    }
    
    #pragma mark  集成第一步: 初始化,  参数:appkey  ,尽可能早的初始化appkey.
    /**
    * 初始化sdk
    */ 
    - (void)initSdk:(NSString *)appKey result:(FlutterResult)result{
        [MQManager initWithAppkey:appKey completion:^(NSString *clientId, NSError *error) {
            if (!error) {
              NSLog(@"美洽 SDK:初始化成功");
            } else {
              NSLog(@"error:%@",error);
            }
        }];
    }
    
    #pragma mark  集成第五步: 跳转到聊天界面
    /**
    * 初始化聊天页面 isPush 为 iOS 跳转方式 默认present
    */ 
    - (void)pushToMeiqiaVCWith:(NSNumber* ) isPush{
    
        UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
        MQChatViewManager *chatViewManager = [[MQChatViewManager alloc] init];
        [chatViewManager setoutgoingDefaultAvatarImage:[UIImage imageNamed:@"meiqia-icon"]];
        if (isPush.boolValue) {
            [chatViewManager pushMQChatViewControllerInViewController:viewController];
        }else {
            [chatViewManager presentMQChatViewControllerInViewController:viewController];
        }
        
    }
    
    #pragma mark - AppDelegate
    - (void)applicationWillEnterForeground:(UIApplication *)application {
    #pragma mark  集成第二步: 进入前台 打开meiqia服务
        [MQManager openMeiqiaService];
    }
    - (void)applicationDidEnterBackground:(UIApplication *)application {
    #pragma mark  集成第三步: 进入后台 关闭美洽服务
        [MQManager closeMeiqiaService];
    }
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    #pragma mark  集成第四步: 上传设备deviceToken
        [MQManager registerDeviceToken:deviceToken];
    }
    
    @end
    
    

    安卓实现路径
    android/src/main/java/com/kefu/ding/meiqiachat/MeiqiachatPlugin.java
    具体实现

    package com.kefu.ding.meiqiachat;
    
    import io.flutter.plugin.common.MethodCall;
    import io.flutter.plugin.common.MethodChannel;
    import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
    import io.flutter.plugin.common.MethodChannel.Result;
    import io.flutter.plugin.common.PluginRegistry.Registrar;
    
    import android.content.Intent;
    
    import com.meiqia.core.MQManager;
    import com.meiqia.core.callback.OnInitCallback;
    import com.meiqia.meiqiasdk.util.MQConfig;
    import com.meiqia.meiqiasdk.util.MQIntentBuilder;
    
    
    /** MeiqiachatPlugin */
    public class MeiqiachatPlugin implements MethodCallHandler {
    
      /// 获取context
      private Registrar registrar;
      private MethodChannel channel;
      public static MeiqiachatPlugin instance;
    
      /** Plugin registration. */
      public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "meiqiachat");
        channel.setMethodCallHandler(new MeiqiachatPlugin(registrar,channel));
      }
    
      private MeiqiachatPlugin(Registrar registrar,MethodChannel channel) {
        this.registrar = registrar;
        this.channel = channel;
        instance = this;
      }
    
      @Override
      public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("initMeiqiaSdk")) {
          setup(call, result);
        } else if (call.method.equals("toChat")) {
          toChat(call, result);
        } else {
          result.notImplemented();
        }
      }
    
      /**
      * 初始化sdk
      */ 
      public void setup(MethodCall call, Result result) {
        MQManager.setDebugMode(true);
        String meiqiaKey = call.arguments.toString();
        MQConfig.init(registrar.context(), meiqiaKey, new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {
            }
            @Override
            public void onFailure(int code, String message) {
            }
        });
      }
    
      /**
      * 初始化聊天页面 isPush 为 iOS 跳转方式 默认present 
      */ 
      public void toChat(MethodCall call, Result result) {
        Intent intent = new MQIntentBuilder(registrar.context()).build();
        registrar.context().startActivity(intent);
      }
      
    }
    
    

    第五步example 中测试

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:meiqiachat/meiqiachat.dart';
    
    void main() {
      return runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      void initState() {
        super.initState();
        initMeiqia();
      }
    
      Future<void> initMeiqia() async {
        try {
          await Meiqiachat.initMeiqiaSdkWith('f5c8d2a0ac4294e654dfba9893295f34');
        } catch (e) {}
      }
    
      // Platform messages are asynchronous, so we initialize in an async method.
      void _toChat() async {
        await Meiqiachat.toChat();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Plugin example app'),
            ),
            body: Center(
              child: FlatButton(
                child: Text('toChat'),
                onPressed: () => _toChat(),
              ),
            ),
          ),
        );
      }
    }
    
    

    第六步 上传

    上传需要完善
    pubspec 中用户信息和仓库信息

    author: loself <loselfmin@gmail.com>
    homepage: https://github.com/Xingefb/meiqiachat
    

    1、测试上传是否有问题
    flutter packages pub publish --dry-run
    2、检查CHANGELOG.md 和pubspec.yaml 中的版本是否一致
    3、上传(全局翻墙、全局翻墙、全局翻墙)
    一、flutter packages pub publish
    此方法只会返回最终结果
    二、sudo flutter packages pub publish -v
    此方法会查看上传进度

    第一次需要网页授权登陆,出现授权连接需要点击跳转网页授权登陆,登陆成功后后问你是否准备充足,继续即可。

    完成后需要稍等然后搜索即可点击搜索
    GitHub
    Pub.dev
    商务合作:loselfmin@gmail.com

    相关文章

      网友评论

        本文标题:Flutter Plugin 集成三方库开发教程

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