iOS Native混編Flutter交互實踐

開篇

圖形性能對比.jpg

開局一張圖,其餘全靠_?ios

目前flutter框架還比較新,又是谷歌家的東西,因此網上的文章基本都是講安卓和flutter混合開發的,沒有iOS和Flutter混合開發的比較詳細的步驟實操。git

混編的前提是你的電腦必須有flutter環境,不會配的請先谷歌教程配置完後再來查看此混編教程。github

正題

由於本文要講的是iOS,因此正常狀況下的環境是macOS + Xcode + flutter環境(v0.8.2-beta);再加上flutter 須要的的dart語言編輯器 Android Studio 、IntelliJ IDEA 或 Visual Studio Code (VS Code) ;由於flutter是多平臺,因此也要安裝安卓相關的SDK。objective-c

本教程是基於flutter環境版本v0.8.2-betaxcode

環境配好後,命令行輸入:flutter doctor -v , 確保FlutterAndroid toolchainiOS toolchainConnected devices (鏈接中的設備,這個列表是你打開你Xcode虛擬機或者安卓虛擬機的時候纔會有) 都不是[✗]這個符號,則說明你的環境OK了 【也要注意編輯器的flutter環境】app

flutter doctor.png

Xcode工程項目配置

Xcode項目的開始

最權威的教程固然是flutter自家的混編wiki,iOS部分我英文理解能力不是很好,實際操做的時候也按照教程操做了一遍,再和網上教程總結了一遍,一路踏坑而出。框架

  • Flutter混合開發還不支持bit code,因此在iOS工程檢查項目並關閉bit code

關閉項目bitcode.png

  • flutter module建立 (不要耦合近Xcode項目中,最好放到與項目目錄同級)

這裏由於使用的是flutter環境(v0.8.2-beta),應該也是很新的分支。看網上說明flutter的master纔是最新的分支。先用beta建立module,若是建立不成功再切換master分支進行建立async

create flutter module.png

目錄結構.png

若是建立不成功,請切換master分支試一下;執行flutter channel master編輯器

  • flutter module 重要文件分析 (部分是隱藏文件,記得查看所有)

flutter module文件分析.png

flutter內部文件分析.png

  • 建立Xcode項目中的Config文件,引向flutter moduleide

    新建Config目錄,管理Xcode工程的配置銜接文件,分別建立 Flutter.xcconfigDebug.xcconfigRelease.xcconfig 三個配置文件;其中Flutter.xcconfig 是指向外目錄flutter module的Generated.xcconfig 文件路徑引用文件,其餘兩個表明Xcode的環境配置文件。

新建膠水配置文件.png

  • 三個文件的引入內容 (所引用的都是絕對路徑,最終都是指引到Generated.xcconfig

In Flutter.xcconfig:

#include "../../flutter_module/.ios/Flutter/Generated.xcconfig"
ENABLE_BITCODE=NO
複製代碼

In Debug.xcconfig:

#include "Flutter.xcconfig"
複製代碼

In Release.xcconfig:

#include "Flutter.xcconfig"
FLUTTER_BUILD_MODE=release
複製代碼

這裏有個值得注意的地方,若是你是使用的pod管理你的項目,則Debug.xcconfigRelease.xcconfig 都須要添加一行pod的引用

  • Xcode project環境配置選擇

Xcode 項目配置選擇.png

  • 最重要: 引入xcode-backend.sh

在iOS工程裏添加運行腳本 "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build,而且確保Run Script這一行在"Target dependencies" 或者 "Check Pods Manifest.lock"後面。

引入xcode-backend.png

此時點擊Xcode的運行,會執行到xcode-backend.sh腳本;此時在iOS工程目錄,也會生成一個Flutter文件夾,裏面是Flutter工程的產物(這個就是flutter最終與Native交互的產物)

  • 添加flutter編譯產物

右鍵項目 - Add Files to 'xxx' 【Options先選Create groups】,選擇Flutter目錄

添加flutter編譯產物.png

可是flutter_assets 並不能使用Create groups 的方式添加,只能使用Creat folder references 的方式添加進Xcode項目內,不然跳轉flutter會頁面渲染失敗(頁面空白)。

flutter_assets特殊處理1.png
應該刪除 flutter_assets,文件夾再 Add Files to 'xxx',選擇 Creat folder references ;最終以下圖

flutter_assets特殊處理.png

將iOS工程目錄下的Flutter文件夾添加到工程,而後確保文件夾下的兩個framework添加到Embeded Binaries

flutter framework引入.png

至此,Xcode與Flutter之間混編配置完成,兩個項目文件已經關聯上了。這時候你就能夠修改main.dart 文件內容,從新編譯運行Xcode 則APP.framework自動會被編譯成最新的flutter代碼。

項目中使用pod管理狀況

1、舊項目沒使用pod管理,混編後又想pod管理

  • 一、先刪除Xcode工程項目中的Run Script
  • 二、pod init
  • 三、在生成的pod file文件寫你要增長的第三方框架,如pod 'AFNetworking’
  • 四、pod install
  • 五、(使用.xcworkspace打開項目)從新配置Run Script
  • 六、修改Debug.xcconfigRelease。xcconfig 都須要增長一行pod config文件引用:(本身查看本身的Pods目錄文件路徑, release就使用.release.xcconfig)
#include "Flutter.xcconfig"
// 下面爲pod引入須要增長的一行
#include "Pods/Target Support Files/Pods-iOSBridgeFlutterDemo/Pods-iOSBridgeFlutterDemo.debug.xcconfig"
複製代碼
  • 七、項目從新編譯,Success

2、若是舊項目已經使用pod管理

  • 若是項目ignore Pods文件夾, 則走一方法中的一、四、五、六、7步驟
  • 若是項目Pods文件夾存在,則走一方法中的六、7步驟

PS: 每次pod update或者pod install都會報錯,由於Run Script的緣由,因此每次添加或更新pod都得刪除Run Script更新pod再添加回Run Script(一、四、六、7步驟);這些繁瑣的操做不知道有沒有辦法避免,知道的朋友能夠回覆一下?不吝賜教,謝謝!

Xcode 與 Flutter 交互

AppDelegate 改造

改造AppDelegate.h,使其繼承FlutterAppDelegate:

#import <Flutter/Flutter.h>

@interface AppDelegate : FlutterAppDelegate <UIApplicationDelegate, FlutterAppLifeCycleProvider>

@end
複製代碼

改造AppDelegate.m

#import "AppDelegate.h"

@interface AppDelegate ()
    
@end

@implementation AppDelegate
{
  FlutterPluginAppLifeCycleDelegate *_lifeCycleDelegate;
}
    
- (instancetype)init {
    if (self = [super init]) {
        _lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init];
    }
    return self;
}
    
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions];
}
    
- (void)applicationDidEnterBackground:(UIApplication*)application {
    [_lifeCycleDelegate applicationDidEnterBackground:application];
}
    
- (void)applicationWillEnterForeground:(UIApplication*)application {
    [_lifeCycleDelegate applicationWillEnterForeground:application];
}
    
- (void)applicationWillResignActive:(UIApplication*)application {
    [_lifeCycleDelegate applicationWillResignActive:application];
}
    
- (void)applicationDidBecomeActive:(UIApplication*)application {
    [_lifeCycleDelegate applicationDidBecomeActive:application];
}
    
- (void)applicationWillTerminate:(UIApplication*)application {
    [_lifeCycleDelegate applicationWillTerminate:application];
}
    
- (void)application:(UIApplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
    [_lifeCycleDelegate application:application
didRegisterUserNotificationSettings:notificationSettings];
}
    
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    [_lifeCycleDelegate application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
    
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    [_lifeCycleDelegate application:application
       didReceiveRemoteNotification:userInfo
             fetchCompletionHandler:completionHandler];
}
    
- (BOOL)application:(UIApplication*)application
            openURL:(NSURL*)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options {
    return [_lifeCycleDelegate application:application openURL:url options:options];
}
    
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
    return [_lifeCycleDelegate application:application handleOpenURL:url];
}
    
- (BOOL)application:(UIApplication*)application
            openURL:(NSURL*)url
  sourceApplication:(NSString*)sourceApplication
         annotation:(id)annotation {
    return [_lifeCycleDelegate application:application
                                   openURL:url
                         sourceApplication:sourceApplication
                                annotation:annotation];
}
    
- (void)application:(UIApplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
  completionHandler:(void (^)(BOOL succeeded))completionHandler NS_AVAILABLE_IOS(9_0) {
    [_lifeCycleDelegate application:application
       performActionForShortcutItem:shortcutItem
                  completionHandler:completionHandler];
}
    
- (void)application:(UIApplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
  completionHandler:(nonnull void (^)(void))completionHandler {
    [_lifeCycleDelegate application:application
handleEventsForBackgroundURLSession:identifier
                  completionHandler:completionHandler];
}
    
- (void)application:(UIApplication*)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    [_lifeCycleDelegate application:application performFetchWithCompletionHandler:completionHandler];
}
    
- (void)addApplicationLifeCycleDelegate:(NSObject<FlutterPlugin>*)delegate {
    [_lifeCycleDelegate addDelegate:delegate];
}

#pragma mark - Flutter
    // Returns the key window's rootViewController, if it's a FlutterViewController.
    // Otherwise, returns nil.
- (FlutterViewController*)rootFlutterViewController {
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([viewController isKindOfClass:[FlutterViewController class]]) {
        return (FlutterViewController*)viewController;
    }
    return nil;
}
    
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    [super touchesBegan:touches withEvent:event];
    
    // Pass status bar taps to key window Flutter rootViewController.
    if (self.rootFlutterViewController != nil) {
        [self.rootFlutterViewController handleStatusBarTouches:event];
    }
}

@end

複製代碼

Flutter主動,Native被動 (MethodChannel)

Flutter 代碼: 引入import 'package:flutter/services.dart';

請用下面代碼替換class _MyHomePageState extends State<MyHomePage> 這個類內容

class _MyHomePageState extends State<MyHomePage> {

  // 建立一個給native的channel (相似iOS的通知)
  static const methodChannel = const MethodChannel('com.pages.your/native_get');

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;

      print('flutter的log打印:如今輸出count=$_counter');
      // 當個數累積到3的時候給客戶端發參數
      if(_counter == 3) {
        _toNativeSomethingAndGetInfo();
      }

      // 當個數累積到5的時候給客戶端發參數
      if(_counter == 1002) {
        Map<String, String> map = { "title": "這是一條來自flutter的參數" };
        methodChannel.invokeMethod('toNativePush',map);
      }

      // 當個數累積到8的時候給客戶端發參數
      if(_counter == 1005) {
        Map<String, dynamic> map = { "content": "flutterPop回來","data":[1,2,3,4,5]};
        methodChannel.invokeMethod('toNativePop',map);
      }
    });
  }

  // 給客戶端發送一些東東 , 而且拿到一些東東
  Future<Null> _toNativeSomethingAndGetInfo() async {
    dynamic result;
    try {
      result = await methodChannel.invokeMethod('toNativeSomething','大佬你點擊了$_counter下');
    } on PlatformException {
      result = 100000;
    }
    setState(() {
      // 類型判斷
      if (result is int) {
        _counter = result;
      }

    });
  }

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
// appBar: new AppBar(
// // Here we take the value from the MyHomePage object that was created by
// // the App.build method, and use it to set our appbar title.
// title: new Text(widget.title),
// ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

複製代碼

Native 代碼:

- (void)pushFlutterViewController {
        FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
        flutterViewController.navigationItem.title = @"Flutter Demo";
            __weak __typeof(self) weakSelf = self;
        
        // 要與main.dart中一致
        NSString *channelName = @"com.pages.your/native_get";
        
            FlutterMethodChannel *messageChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:flutterViewController];
        
            [messageChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
                // call.method 獲取 flutter 給回到的方法名,要匹配到 channelName 對應的多個 發送方法名,通常須要判斷區分
                // call.arguments 獲取到 flutter 給到的參數,(好比跳轉到另外一個頁面所須要參數)
                // result 是給flutter的回調, 該回調只能使用一次
                NSLog(@"flutter 給到我:\nmethod=%@ \narguments = %@",call.method,call.arguments);
                
                if ([call.method isEqualToString:@"toNativeSomething"]) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"flutter回調" message:[NSString stringWithFormat:@"%@",call.arguments] delegate:self cancelButtonTitle:@"肯定" otherButtonTitles:nil];
                    [alertView show];
                    
                    // 回調給flutter
                    if (result) {
                        result(@1000);
                    }
                } else if ([call.method isEqualToString:@"toNativePush"]) {
                    ThirdViewController *testVC = [[ThirdViewController alloc] init];
                    testVC.parames = call.arguments;
                    [weakSelf.navigationController pushViewController:testVC animated:YES];
                } else if ([call.method isEqualToString:@"toNativePop"]) {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            }];
        
        [self.navigationController pushViewController:flutterViewController animated:YES];
    }
複製代碼

Native主動,Flutter被動 (EventChannel)

通常用於flutter初始化須要從客戶端獲取一些參數做爲渲染條件;相似iOS這邊的KVO,監聽flutter是否已經在監聽,監聽的時候回調到代理【這步其實仍是flutter監聽的時候,內部發了一個通知,iOS這邊收到並回調】,iOS Native處理代理,並回調給flutter所須要參數

Flutter 代碼 (class中):

// 註冊一個通知
  static const EventChannel eventChannel = const EventChannel('com.pages.your/native_post');

  // 渲染前的操做,相似viewDidLoad
  @override
  void initState() {
    super.initState();
    
    // 監聽事件,同時發送參數12345
    eventChannel.receiveBroadcastStream(12345).listen(_onEvent,onError: _onError);
  }

  String naviTitle = '你好,大佬' ;
  // 回調事件
  void _onEvent(Object event) {
    setState(() {
      naviTitle =  event.toString();
    });
  }
  // 錯誤返回
  void _onError(Object error) {

  }
複製代碼

Native代碼:

- (void)pushFlutterViewController_EventChannel {
        FlutterViewController* flutterViewController = [[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
        flutterViewController.navigationItem.title = @"EventChannel Demo";
        // 要與main.dart中一致
        NSString *channelName = @"com.pages.your/native_post";
        
        FlutterEventChannel *evenChannal = [FlutterEventChannel eventChannelWithName:channelName binaryMessenger:flutterViewController];
        // 代理
        [evenChannal setStreamHandler:self];
        
        [self.navigationController pushViewController:flutterViewController animated:YES];
    }

#pragma mark - <FlutterStreamHandler>
    // // 這個onListen是Flutter端開始監聽這個channel時的回調,第二個參數 EventSink是用來傳數據的載體。
    - (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                           eventSink:(FlutterEventSink)events {
        
        // arguments flutter給native的參數
        // 回調給flutter, 建議使用實例指向,由於該block可使用屢次
        if (events) {
            events(@"我是標題");
        }
        return nil;
    }
    
    /// flutter再也不接收
    - (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
        // arguments flutter給native的參數
        return nil;
 }
 
複製代碼

交互總結

這兩種方式都差很少,一個使用的時候使用block,一個使用的時候使用delegate;最終回調給flutter的都是經過block。

MethodChannel 使用block,上下文更加明確;同一個channel name能夠根據flutter給回的call.methodcall.arguments更加靈活的處理回調handle, 回調只能使用一次(意思就是就算你建立一個實例指向block,單block回調只能使用一次,回調以後flutter block那邊再也不接收);

EventChannel 使用delegate,代碼層次更鮮明;同一個channel name只能經過判斷arguments參數處理回調handle, 回調可使用屢次(建立一個實例指向block,該block能夠向flutter發送屢次);

BasicMessageChannel 請自行學習。

疑問

建立使用FlutterViewController Xcode的Memory一直在增長到一個水平,分類重寫- (void)dealloc 也沒有進來,估計是內存泄漏了。因而去查了官方的Issues ,確實有幾個關聯:

Native 簡單push FlutterViewControllerpop回,內存到達一個階段後不降,FlutterViewController不會執行dealloc方法。不知道這誰知道有沒有解決方案?不吝賜教,謝謝!

學習

相關文章
相關標籤/搜索