添加Flutter到现有iOS的项目

添加Flutter到现有iOS的项目

创建iOS项目

如果你已经有iOS项目,可以直接使用。这里我们先创建一个空的iOS项目来模拟已有的项目,取名叫TestOne

创建Flutter模块

进入你的项目同一层目录,假如你的项目是在…path1/path2/yourApp,那么你应该进入到path2目录中

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

上面的命令会创建一个flutter的项目模块,在flutter文件夹中有一个.ios的隐藏文件夹,里面包裹了Cocoapods 和 Ruby 脚本。

完成后的项目目录是这样的:

将Flutter模块作为依赖添加到主项目

添加Flutter需要使用cocoapods,如果你还没有安装,可以参考这里的详细教程:安装cocoapods

创建Podfile文件

如果你的工程已经使用了Cocoapods,就可以跳过此步骤。
安装完成之后,切换到工程的文件夹下:

cd 工程路径

初始化pod的环境:

pod init

此时工程中会出现一个Podfile文件,添加项目依赖的第三方库就在这个文件中配置。

编辑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模块路径。
运行

pod install

配置build phase,为编译Dart 代码添加编译选项

打开iOS项目,选中TestOne项目的Build Phases选项,点击左上角+号按钮,选择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

如下图所示:

然后需要编译一下项目:Command + B
如果你遇到了类似的这个问题:

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

将Enable BitCode关掉就行,因为目前Flutter目前还不支持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这个文件:

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已经是继承于别的类的时候,可以通过让你的delegate实现FlutterAppLifeCycleProvider协议:

#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

然后生命周期方法应该由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中添加测试代码:

#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)
  }
}

现在运行代码,点击按钮,就能看到一个全屏的Flutter界面在你的app上。
你也可以设置路由跳转的别的组件上:
* Objective-C:

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

你可以在展示FlutterViewController之前,在Dart代码中使用SystemNavigator.pop()将其弹出展示栈(就像iOS原生那样)。

例子截图:

点击按钮跳转到flutter页面:

使用热重载的方法

热重载指的是不用重新启动就看到修改后的效果,类似web网页开发时保存就看到效果的方式。
进入flutter模块,执行命令:

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

接下来在xcode中启动你的app,进入到flutter的页面,此时你应该在控制台(终端)看到如下信息:

🔥 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”.

你可以在my_flutter中编辑Dart code,然后在终端输入r来使用热重载。你也可以在浏览器中输入上面的URL来查看断点、分析内存和其他的调试任务。

欢迎继续学习相关的其他系列教程,关注我们TryEnough

demo工程下载

文件信息:
文件名称:添加Flutter到现有iOS的项目Demo
下载地址:
点击去下载

这篇文章有 7 个评论

  1. 这里都是空项目集成flutter,我是在原来项目中集成,最后flutter项目中代码是空项目,所有原生代码怎么倒入flutter项目呢

  2. 怎么会那么多人用手动集成Flutter,pod 多方便呢,之前搞了下,然后换路径了,可以启动,但是没法渲染UI,在这里找到答案了,感谢,完了我也整理一篇用Pod导入的

  3. 我使用VSCode创建的flutter项目没有 隐藏的 .ios 和 .android 反而是真实文件夹

    1. 那也不用担心的哈

    1. 不好意思,看到信息晚了。我不明白你指的是哪个demo,我建议你到https://tryenough.com/type-flutter找找有没有你想要的。

    2. 你好,谢谢你的反馈,我稍后会将demo工程下载放在 http://tryenough.com/flutter03 文章底部。(大概2019-01-23下午5:45分前完成。)

发表评论

关闭菜单