添加Flutter到現(xiàn)有iOS的項(xiàng)目


添加Flutter到現(xiàn)有iOS的項(xiàng)目


創(chuàng)建iOS項(xiàng)目

如果你已經(jīng)有iOS項(xiàng)目,可以直接使用。這里我們先創(chuàng)建一個(gè)空的iOS項(xiàng)目來模擬已有的項(xiàng)目,取名叫TestOne

創(chuàng)建Flutter模塊

進(jìn)入你的項(xiàng)目同一層目錄,假如你的項(xiàng)目是在...path1/path2/yourApp,那么你應(yīng)該進(jìn)入到path2目錄中

$ cd ...path1/path2/
$ flutter create -t module my_flutter

上面的命令會(huì)創(chuàng)建一個(gè)flutter的項(xiàng)目模塊,在flutter文件夾中有一個(gè).ios的隱藏文件夾,里面包裹了Cocoapods 和 Ruby 腳本。

完成后的項(xiàng)目目錄是這樣的:


將Flutter模塊作為依賴添加到主項(xiàng)目

添加Flutter需要使用cocoapods,如果你還沒有安裝,可以參考這里的詳細(xì)教程:安裝cocoapods

創(chuàng)建Podfile文件

如果你的工程已經(jīng)使用了Cocoapods,就可以跳過此步驟。
安裝完成之后,切換到工程的文件夾下:

cd 工程路徑

初始化pod的環(huán)境:

pod init

此時(shí)工程中會(huì)出現(xiàn)一個(gè)Podfile文件,添加項(xiàng)目依賴的第三方庫就在這個(gè)文件中配置。

編輯Podfile文件添加最后兩行代碼:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'TestOne' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for TestOne

  target 'TestOneTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'TestOneUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

#新添加的代碼
flutter_application_path = '../my_flutter'
eval(File.read(File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')), binding)

其中flutter_application_path代表你的flutter模塊路徑。
運(yùn)行

pod install

為編譯Dart 代碼添加build phase

打開iOS項(xiàng)目,選中TARGETTestOne項(xiàng)目的Build Phases選項(xiàng),點(diǎn)擊左上角+號(hào)按鈕,選擇New Run Script Phase,將下面的shell腳本添加到輸入框中:

"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" build
"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed

如下圖所示:


然后需要編譯一下項(xiàng)目:Command + B
如果你遇到了類似的這個(gè)問題:

FlutterPluginRegistrant/libFlutterPluginRegistrant.a(GeneratedPluginRegistrant.o)' does not contain bitcode.You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.for architecture arm64

將EnableBitCode關(guān)掉就行,因?yàn)槟壳癋lutter目前還不支持BitCode。

在主app中使用FlutterViewController

修改AppDelegate.h繼承自FlutterAppDelegate:

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

@interface AppDelegate : FlutterAppDelegate
@end

修改AppDelegate.m文件:

#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Only if you have Flutter Plugins

#include "AppDelegate.h"

@implementation AppDelegate

// This override can be omitted if you do not have any Flutter Plugins.
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

如果你是Swift代碼,可以修改AppDelegate.swift這個(gè)文件:

import UIKit
import Flutter
import FlutterPluginRegistrant // Only if you have Flutter Plugins.

@UIApplicationMain
class AppDelegate: FlutterAppDelegate {

  // Only if you have Flutter plugins.
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    GeneratedPluginRegistrant.register(with: self);
    return super.application(application, didFinishLaunchingWithOptions: launchOptions);
  }

}

但是如果你的delegate已經(jīng)是繼承于別的類的時(shí)候,可以通過讓你的delegate實(shí)現(xiàn)FlutterAppLifeCycleProvider協(xié)議:

#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h> // Only if you have Flutter Plugins

@interface AppDelegate : UIResponder <UIApplicationDelegate, FlutterAppLifeCycleProvider>
@property (strong, nonatomic) UIWindow *window;
@end

然后生命周期方法應(yīng)該由FlutterPluginAppLifeCycleDelegate來代理:

@implementation AppDelegate
{
    FlutterPluginAppLifeCycleDelegate *_lifeCycleDelegate;
}

- (instancetype)init {
    if (self = [super init]) {
        _lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init];
    }
    return self;
}

- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    [GeneratedPluginRegistrant registerWithRegistry:self]; // Only if you are using Flutter plugins.
    return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions];
}

// 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];
    }
}

- (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];
}
@end

使用FlutterViewController

ViewController.m中添加測(cè)試代碼:

#import <Flutter/Flutter.h>
#import "ViewController.h"

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(handleButtonAction)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Press me" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];
}

- (void)handleButtonAction {
    FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
    [self presentViewController:flutterViewController animated:false completion:nil];
}
@end

swift版:

import UIKit
import Flutter

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let button = UIButton(type:UIButtonType.custom)
    button.addTarget(self, action: #selector(handleButtonAction), for: .touchUpInside)
    button.setTitle("Press me", for: UIControlState.normal)
    button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
    button.backgroundColor = UIColor.blue
    self.view.addSubview(button)
  }

  @objc func handleButtonAction() {
    let flutterViewController = FlutterViewController()
    self.present(flutterViewController, animated: false, completion: nil)
  }
}

現(xiàn)在運(yùn)行代碼,點(diǎn)擊按鈕,就能看到一個(gè)全屏的Flutter界面在你的app上。
你也可以設(shè)置路由跳轉(zhuǎn)的別的組件上:

  • Objective-C:
[flutterViewController setInitialRoute:@"route1"];
  • Swift:
flutterViewController.setInitialRoute("route1")

你可以在展示FlutterViewController之前,在Dart代碼中使用SystemNavigator.pop()將其彈出展示棧(就像iOS原生那樣)。

例子截圖:


點(diǎn)擊按鈕跳轉(zhuǎn)到flutter頁面:

使用熱重載的方法

熱重載指的是不用重新啟動(dòng)就看到修改后的效果,類似web網(wǎng)頁開發(fā)時(shí)保存就看到效果的方式。
進(jìn)入flutter模塊,執(zhí)行命令:

$ cd some/path/my_flutter
$ flutter attach
Waiting for a connection from Flutter on iPhone XR...

接下來在xcode中啟動(dòng)你的app,進(jìn)入到flutter的頁面,此時(shí)你應(yīng)該在控制臺(tái)(終端)看到如下信息:

<table><tr><td bgcolor=#D1EEEE>?? To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
An Observatory debugger and profiler on Android SDK built for x86 is available at: http://127.0.0.1:61513/
For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".
</td></tr></table>

你可以在my_flutter中編輯Dart code,然后在終端輸入r來使用熱重載。你也可以在瀏覽器中輸入上面的URL來查看斷點(diǎn)、分析內(nèi)存和其他的調(diào)試任務(wù)。

歡迎繼續(xù)學(xué)習(xí)相關(guān)的其他系列教程,關(guān)注我們TryEnough

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 如何在現(xiàn)有的iOS工程中接入Flutter(詳見原文) 本文是參考 官方文檔,加上自己的爬坑經(jīng)驗(yàn),總結(jié)出的,供大家...
    Andy__M閱讀 9,899評(píng)論 21 31
  • 本文翻譯自 Add-Flutter-to-existing-apps 在已有項(xiàng)目中繼承Flutter 約定:本文中...
    黃二瓜閱讀 9,264評(píng)論 3 21
  • 一直想給小貓寫點(diǎn)什么,不知道從哪里寫起。其實(shí)一開始我對(duì)博物館后院的這個(gè)常住居民不感興趣,更加沒有什么情感上的牽...
    徐蔻初閱讀 1,394評(píng)論 3 15
  • 威海是一座美麗的海濱城市,海自然就成了威海的一道奇麗風(fēng)景。 萬里無云,風(fēng)和日...
    李芬芬閱讀 377評(píng)論 0 1

友情鏈接更多精彩內(nèi)容