開篇
開局一張圖膳叨,其他全靠_?
目前flutter框架還比較新,又是谷歌家的東西兄春,所以網(wǎng)上的文章基本都是講安卓和flutter混合開發(fā)的,沒有iOS和Flutter混合開發(fā)的比較詳細的步驟實操锡溯。
混編的前提是你的電腦必須有flutter環(huán)境赶舆,不會配的請先谷歌教程配置完后再來查看此混編教程。
正題
因為本文要講的是iOS祭饭,所以正常情況下的環(huán)境是macOS + Xcode + flutter環(huán)境(v0.8.2-beta)芜茵;再加上flutter 需要的的dart語言編輯器 Android Studio 、IntelliJ IDEA 或 Visual Studio Code (VS Code) 甜癞;因為flutter是多平臺夕晓,所以也要安裝安卓相關(guān)的SDK。
本教程是基于flutter環(huán)境版本v0.8.2-beta
環(huán)境配好后悠咱,命令行輸入:flutter doctor -v
, 確保Flutter
蒸辆、 Android toolchain
、iOS toolchain
析既、 Connected devices
(連接中的設(shè)備躬贡,這個列表是你打開你Xcode虛擬機或者安卓虛擬機的時候才會有) 都不是[?]這個符號,則說明你的環(huán)境OK了 【也要注意編輯器的flutter環(huán)境】
Xcode工程項目配置
Xcode項目的開始
最權(quán)威的教程當(dāng)然是flutter自家的混編wiki眼坏,iOS部分我英文理解能力不是很好拂玻,實際操作的時候也按照教程操作了一遍,再和網(wǎng)上教程總結(jié)了一遍宰译,一路踏坑而出檐蚜。
- Flutter混合開發(fā)還不支持bit code,所以在iOS工程檢查項目并關(guān)閉bit code
- flutter module創(chuàng)建 (不要耦合近Xcode項目中沿侈,最好放到與項目目錄同級)
這里因為使用的是flutter環(huán)境(v0.8.2-beta)闯第,應(yīng)該也是很新的分支∽菏茫看網(wǎng)上說明flutter的master才是最新的分支咳短。先用beta創(chuàng)建module,如果創(chuàng)建不成功再切換master分支進行創(chuàng)建
如果創(chuàng)建不成功蛛淋,請切換master分支試一下咙好;執(zhí)行
flutter channel master
- flutter module 重要文件分析 (部分是隱藏文件,記得查看全部)
-
創(chuàng)建Xcode項目中的Config文件褐荷,引向flutter module
新建
Config
目錄勾效,管理Xcode工程的配置銜接文件,分別創(chuàng)建Flutter.xcconfig
、Debug.xcconfig
层宫、Release.xcconfig
三個配置文件绘迁;其中Flutter.xcconfig
是指向外目錄flutter module的Generated.xcconfig
文件路徑引用文件,其他兩個代表Xcode的環(huán)境配置文件卒密。
- 三個文件的引入內(nèi)容 (所引用的都是絕對路徑缀台,最終都是指引到
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.xcconfig
膛腐、Release.xcconfig
都需要添加一行pod的引用
- Xcode project環(huán)境配置選擇
- 最重要: 引入
xcode-backend.sh
在iOS工程里添加運行腳本(創(chuàng)建Run Scrip) "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
,并且確保Run Script
這一行在"Target dependencies"
或者 "Check Pods Manifest.lock"
后面鼎俘。
此時點擊Xcode的運行哲身,會執(zhí)行到xcode-backend.sh
腳本;此時在iOS工程目錄贸伐,也會生成一個Flutter文件夾勘天,里面是Flutter工程的產(chǎn)物(這個就是flutter最終與Native交互的產(chǎn)物)
- 添加flutter編譯產(chǎn)物
右鍵項目 - Add Files to 'xxx'
【Options先選Create groups
】,選擇Flutter
目錄
但是flutter_assets
并不能使用Create groups
的方式添加捉邢,只能使用Creat folder references
的方式添加進Xcode項目內(nèi)脯丝,否則跳轉(zhuǎn)flutter會頁面渲染失敗(頁面空白)伏伐。
應(yīng)該刪除
flutter_assets
宠进,文件夾再Add Files to 'xxx'
,選擇Creat folder references
藐翎;最終如下圖
將iOS工程目錄下的Flutter文件夾添加到工程材蹬,然后確保文件夾下的兩個framework添加到Embeded Binaries
里
至此,Xcode與Flutter之間混編配置完成吝镣,兩個項目文件已經(jīng)關(guān)聯(lián)上了堤器。這時候你就可以修改main.dart
文件內(nèi)容,重新編譯運行Xcode 則APP.framework
自動會被編譯成最新的flutter代碼末贾。
項目中使用pod管理情況
一闸溃、舊項目沒使用pod管理,混編后又想pod管理
- 1未舟、先刪除Xcode工程項目中的Run Script
- 2圈暗、
pod init
- 3掂为、在生成的pod file文件寫你要增加的第三方框架裕膀,如
pod 'AFNetworking’
- 4、
pod install
- 5勇哗、(使用.xcworkspace打開項目)重新配置Run Script
- 6昼扛、修改
Debug.xcconfig
、Release。xcconfig
都需要增加一行pod config文件引用:(自己查看自己的Pods目錄文件路徑, release就使用.release.xcconfig)
#include "Flutter.xcconfig"
// 下面為pod引入需要增加的一行
#include "Pods/Target Support Files/Pods-iOSBridgeFlutterDemo/Pods-iOSBridgeFlutterDemo.debug.xcconfig"
- 7抄谐、項目重新編譯渺鹦,Success
二、如果舊項目已經(jīng)使用pod管理
- 如果項目ignore Pods文件夾蛹含, 則走一方法中的1毅厚、4、5浦箱、6吸耿、7步驟
- 如果項目Pods文件夾存在,則走一方法中的6酷窥、7步驟
PS: 每次pod update或者pod install都會報錯咽安,因為Run Script的原因,所以每次添加或更新pod都得刪除Run Script更新pod再添加回Run Script(1蓬推、4妆棒、6、7步驟)沸伏;這些繁瑣的操作不知道有沒有辦法避免糕珊,知道的朋友可以回復(fù)一下?不吝賜教毅糟,謝謝放接!
上面的解決辦法是:使用Xcode9.2創(chuàng)建Run Script即可。如果是Xcode 10創(chuàng)建就會出錯(原理不詳留特,估計是Xcode bug)
因為Xcode9.2創(chuàng)建的Run Script沒有inputFileListPaths
和outputFileListPaths
纠脾,而Xcode10創(chuàng)建會有,所以Xcode10創(chuàng)建的小朋友只需要修改project.pbxproj
文件(刪掉兩個字段相關(guān))即可蜕青。
---------混編最新總結(jié)方法請點擊此處苟蹈,建議再看完??有點自己理解再實操-------
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>
這個類內(nèi)容
class _MyHomePageState extends State<MyHomePage> {
// 創(chuàng)建一個給native的channel (類似iOS的通知)
static const methodChannel = const MethodChannel('com.pages.your/native_get');
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
print('flutter的log打踊弁选:現(xiàn)在輸出count=$_counter');
// 當(dāng)個數(shù)累積到3的時候給客戶端發(fā)參數(shù)
if(_counter == 3) {
_toNativeSomethingAndGetInfo();
}
// 當(dāng)個數(shù)累積到5的時候給客戶端發(fā)參數(shù)
if(_counter == 1002) {
Map<String, String> map = { "title": "這是一條來自flutter的參數(shù)" };
methodChannel.invokeMethod('toNativePush',map);
}
// 當(dāng)個數(shù)累積到8的時候給客戶端發(fā)參數(shù)
if(_counter == 1005) {
Map<String, dynamic> map = { "content": "flutterPop回來","data":[1,2,3,4,5]};
methodChannel.invokeMethod('toNativePop',map);
}
});
}
// 給客戶端發(fā)送一些東東 , 并且拿到一些東東
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 對應(yīng)的多個 發(fā)送方法名贺喝,一般需要判斷區(qū)分
// call.arguments 獲取到 flutter 給到的參數(shù)菱鸥,(比如跳轉(zhuǎn)到另一個頁面所需要參數(shù))
// result 是給flutter的回調(diào), 該回調(diào)只能使用一次
NSLog(@"flutter 給到我:\nmethod=%@ \narguments = %@",call.method,call.arguments);
if ([call.method isEqualToString:@"toNativeSomething"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"flutter回調(diào)" message:[NSString stringWithFormat:@"%@",call.arguments] delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alertView show];
// 回調(diào)給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主動躏鱼,F(xiàn)lutter被動 (EventChannel)
一般用于flutter初始化需要從客戶端獲取一些參數(shù)作為渲染條件氮采;類似iOS這邊的KVO,監(jiān)聽flutter是否已經(jīng)在監(jiān)聽染苛,監(jiān)聽的時候回調(diào)到代理【這步其實還是flutter監(jiān)聽的時候鹊漠,內(nèi)部發(fā)了一個通知,iOS這邊收到并回調(diào)】,iOS Native處理代理躯概,并回調(diào)給flutter所需要參數(shù)
Flutter 代碼 (class中):
// 注冊一個通知
static const EventChannel eventChannel = const EventChannel('com.pages.your/native_post');
// 渲染前的操作登钥,類似viewDidLoad
@override
void initState() {
super.initState();
// 監(jiān)聽事件,同時發(fā)送參數(shù)12345
eventChannel.receiveBroadcastStream(12345).listen(_onEvent,onError: _onError);
}
String naviTitle = '你好娶靡,大佬' ;
// 回調(diào)事件
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端開始監(jiān)聽這個channel時的回調(diào)牧牢,第二個參數(shù) EventSink是用來傳數(shù)據(jù)的載體。
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
// arguments flutter給native的參數(shù)
// 回調(diào)給flutter姿锭, 建議使用實例指向结执,因為該block可以使用多次
if (events) {
events(@"我是標題");
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter給native的參數(shù)
return nil;
}
交互總結(jié)
這兩種方式都差不多,一個使用的時候使用block艾凯,一個使用的時候使用delegate献幔;最終回調(diào)給flutter的都是通過block。
MethodChannel
使用block趾诗,上下文更加明確蜡感;同一個channel name
可以根據(jù)flutter給回的call.method
、call.arguments
更加靈活的處理回調(diào)handle, 回調(diào)只能使用一次(意思就是就算你創(chuàng)建一個實例指向block恃泪,單block回調(diào)只能使用一次郑兴,回調(diào)之后flutter block那邊不再接收);
EventChannel
使用delegate贝乎,代碼層次更鮮明情连;同一個channel name
只能通過判斷arguments
參數(shù)處理回調(diào)handle, 回調(diào)可以使用多次(創(chuàng)建一個實例指向block,該block可以向flutter發(fā)送多次)览效;
BasicMessageChannel
請自行學(xué)習(xí)却舀。
疑問
創(chuàng)建使用FlutterViewController
Xcode的Memory一直在增加到一個水平,分類重寫- (void)dealloc
也沒有進來锤灿,估計是內(nèi)存泄漏了挽拔。于是去查了官方的Issues ,確實有幾個關(guān)聯(lián):
- Flutter SSL Memory Leaks #20409
- Unable to release FlutterViewController even when there is nothing referencing it. #21347
Native 簡單push FlutterViewController
但校, pop
回螃诅,內(nèi)存到達一個階段后不降,FlutterViewController
不會執(zhí)行dealloc
方法状囱。不知道這誰知道有沒有解決方案术裸?不吝賜教,謝謝亭枷!