Skip to content

Commit 4ba130c

Browse files
authored
[ios] Use DFS traversal to find engines of a scene automatically (rather than manually manage the engines list) (flutter#192457)
This PR simplifies iOS embedder's UIScene lifecycle logic. The key idea is to perform DFS traversal to find engines to send scene events to (rather than manually manage the `flutterManagedEngines` list). By doing so, we are able to remove the need to manual registering engines (mostly, see below) and other logics too. This PR also fixes a few bugs along the way for both single and multi-scenes. ### Simplifications: [multi-scene] Use DFS to find engines of a scene automatically (rather than manually manage `flutterManagedEngines` list) [multi-scene] Manual register/unregister is only required for cases where FlutterVC is not added to the scene but still wanna receive events (e.g. headless/add-to-app) (Fixes flutter#185689) [single-scene] Remove NSNotification code path for connection events ### Bug fixes [single-scene] Fixes missing connection event for an edge case of implicit engine usage (Fixes flutter#186547) [single-scene] Fix missing lifecycle events if the engine is not attached to any scenes (e.g. headless engines/add-to-app) (Fixes flutter#191907) [multi-scene] connectionOptions should be per scene (Fixes flutter#191039) [multi-scene] Manual register/unregister API is now registered per scene rather than per scene delegate (added `scene` parameter) [multi-scene] Scene lifecycle listeners are not per-scene rather than per scene delegate (Fixes flutter#185687) Also fixes flutter#185688 Also fixes flutter#185702 Also fixes flutter#192344 *If you had to change anything in the [flutter/tests] repo, include a link to the migration guide as per the [breaking change policy].* ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [ ] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 132e1c6 commit 4ba130c

23 files changed

Lines changed: 1112 additions & 834 deletions

‎dev/devicelab/bin/tasks/uiscene_plugin_lifecycle_test_ios.dart‎

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ Future<void> main(List<String> args) async {
121121
templatesDir: templatesDir,
122122
xcodeProjectDir: xcodeProjectDir,
123123
xcodeProjectName: xcodeProjectName,
124+
appDir: appDir,
124125
);
125126
testCount++;
126127
if (result != 0) {
@@ -302,11 +303,13 @@ Future<int> _testNativeApp({
302303
required Directory xcodeProjectDir,
303304
required String deviceId,
304305
required String xcodeProjectName,
306+
required Directory appDir,
305307
}) async {
306308
final String resultBundleTemp = Directory.systemTemp
307309
.createTempSync('flutter_module_test_ios_xcresult.')
308310
.path;
309311
final String resultBundlePath = path.join(resultBundleTemp, 'result');
312+
final String derivedDataPath = path.join(appDir.path, 'build', 'DerivedData');
310313
final int testResultExit = await exec(
311314
'xcodebuild',
312315
<String>[
@@ -318,6 +321,8 @@ Future<int> _testNativeApp({
318321
'Debug',
319322
'-destination',
320323
'id=$deviceId',
324+
'-derivedDataPath',
325+
derivedDataPath,
321326
'-resultBundlePath',
322327
resultBundlePath,
323328
'test',
@@ -494,6 +499,22 @@ class Scenarios {
494499
r'$PLUGIN_DIR/ios/my_plugin/Sources/my_plugin/MyPlugin.swift',
495500
r'$TEMPLATE_DIR/native/UITests-ApplicationEvents-AppNotMigrated.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
496501
},
502+
503+
// Single scene app where FlutterViewController is instantiated with the engine,
504+
// but never added to the scene hierarchy. Engine still receives events automatically.
505+
'SingleScene-FlutterViewControllerNotAddedToScene': <String, String>{
506+
...sharedAppLifecycleFiles,
507+
...sharedPluginLifecycleFiles,
508+
r'$TEMPLATE_DIR/native/AppDelegate-FlutterAppDelegate-FlutterEngine.swift':
509+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/AppDelegate.swift',
510+
r'$TEMPLATE_DIR/native/SceneDelegate-FlutterSceneDelegate.swift':
511+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/SceneDelegate.swift',
512+
r'$TEMPLATE_DIR/native/ViewController-FlutterEngineFromAppDelegate-FlutterViewControllerNotAdded.swift':
513+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/ViewController.swift',
514+
r'$TEMPLATE_DIR/flutterplugin/ios/LifecyclePlugin-migrated.swift':
515+
r'$PLUGIN_DIR/ios/my_plugin/Sources/my_plugin/MyPlugin.swift',
516+
r'$TEMPLATE_DIR/native/UITests-SceneEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
517+
},
497518
};
498519

499520
late Map<String, Map<String, String>> multiSceneScenarios = <String, Map<String, String>>{
@@ -550,6 +571,42 @@ class Scenarios {
550571
r'$PLUGIN_DIR/ios/my_plugin/Sources/my_plugin/MyPlugin.swift',
551572
r'$TEMPLATE_DIR/native/UITests-SceneEvents-NoApplicationEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
552573
},
574+
575+
// Multi scene app where FlutterViewController is never added to the scene hierarchy,
576+
// but the engine is manually registered via registerSceneLifeCycle(with:scene:).
577+
'MultiSceneEnabled-ManualRegistration-FlutterViewControllerNotAddedToScene': <String, String>{
578+
...sharedAppLifecycleFiles,
579+
...sharedPluginLifecycleFiles,
580+
r'$TEMPLATE_DIR/native/Info-MultiSceneEnabled-NoStoryboard.plist':
581+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/Info.plist',
582+
r'$TEMPLATE_DIR/native/AppDelegate-FlutterAppDelegate.swift':
583+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/AppDelegate.swift',
584+
r'$TEMPLATE_DIR/native/SceneDelegate-FlutterSceneDelegate-MultiScene-FlutterViewControllerNotAdded.swift':
585+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/SceneDelegate.swift',
586+
r'$TEMPLATE_DIR/native/ViewController-FlutterEngineFromSceneDelegate-FlutterViewControllerNotAdded.swift':
587+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/ViewController.swift',
588+
r'$TEMPLATE_DIR/flutterplugin/ios/LifecyclePlugin-migrated.swift':
589+
r'$PLUGIN_DIR/ios/my_plugin/Sources/my_plugin/MyPlugin.swift',
590+
r'$TEMPLATE_DIR/native/UITests-SceneEvents-NoApplicationEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
591+
},
592+
593+
// Multi scene app where FlutterViewController is never added to the scene hierarchy,
594+
// but the engine is manually registered via the legacy registerSceneLifeCycle(with:).
595+
'MultiSceneEnabled-LegacyManualRegistration-FlutterViewControllerNotAddedToScene': <String, String>{
596+
...sharedAppLifecycleFiles,
597+
...sharedPluginLifecycleFiles,
598+
r'$TEMPLATE_DIR/native/Info-MultiSceneEnabled-NoStoryboard.plist':
599+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/Info.plist',
600+
r'$TEMPLATE_DIR/native/AppDelegate-FlutterAppDelegate.swift':
601+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/AppDelegate.swift',
602+
r'$TEMPLATE_DIR/native/SceneDelegate-FlutterSceneDelegate-MultiScene-LegacyRegistration-FlutterViewControllerNotAdded.swift':
603+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/SceneDelegate.swift',
604+
r'$TEMPLATE_DIR/native/ViewController-FlutterEngineFromSceneDelegate-FlutterViewControllerNotAdded.swift':
605+
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/ViewController.swift',
606+
r'$TEMPLATE_DIR/flutterplugin/ios/LifecyclePlugin-migrated.swift':
607+
r'$PLUGIN_DIR/ios/my_plugin/Sources/my_plugin/MyPlugin.swift',
608+
r'$TEMPLATE_DIR/native/UITests-SceneEvents-NoApplicationEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
609+
},
553610
};
554611

555612
late Map<String, Map<String, String>> stateRestorationScenarios = <String, Map<String, String>>{
@@ -620,9 +677,8 @@ class Scenarios {
620677

621678
// When using an implicit FlutterEngine, created by the FlutterViewController in another
622679
// ViewController, we expect plugins to be registered after the FlutterViewController is
623-
// created, which results in the `application:didFinishLaunchingWithOptions:` and
624-
// `scene:willConnectToSession:options:` events being missed. This is not a expected use case
625-
// but it could be utilized.
680+
// created, which results in the `application:didFinishLaunchingWithOptions:`. This is not
681+
// ideal, but it is the existing behavior. See: https://github.com/flutter/flutter/issues/186547.
626682
'FlutterImplicitEngineDelegate-AppMigrated-ImplicitFlutterEngine': <String, String>{
627683
...sharedAppLifecycleFiles,
628684
...sharedPluginLifecycleFiles,
@@ -634,7 +690,7 @@ class Scenarios {
634690
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/AppDelegate.swift',
635691
r'$TEMPLATE_DIR/native/ViewController-ImplicitFlutterEngine.swift':
636692
r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperiment/ViewController.swift',
637-
r'$TEMPLATE_DIR/native/UITests-SceneEventsNoConnect-NoApplicationEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
693+
r'$TEMPLATE_DIR/native/UITests-SceneEvents-NoApplicationEvents.swift': r'$XCODE_PROJ_DIR/NativeUIKitSwiftExperimentUITests/NativeUIKitSwiftExperimentUITests.swift',
638694
},
639695
};
640696

‎dev/integration_tests/ios_add2app_uiscene/flutterplugin/ios/LifecyclePlugin-migrated.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ import Flutter
66
import UIKit
77

88
public class MyPlugin: NSObject, FlutterPlugin, FlutterSceneLifeCycleDelegate {
9-
var events = [String]()
9+
public static var instance: MyPlugin?
10+
public var events = [String]()
1011

1112
public static func register(with registrar: FlutterPluginRegistrar) {
1213
let channel = FlutterMethodChannel(
1314
name: "my_plugin",
1415
binaryMessenger: registrar.messenger()
1516
)
1617
let instance = MyPlugin()
18+
MyPlugin.instance = instance
1719
registrar.addMethodCallDelegate(instance, channel: channel)
1820
registrar.addApplicationDelegate(instance)
1921
registrar.addSceneDelegate(instance)

‎dev/integration_tests/ios_add2app_uiscene/flutterplugin/ios/LifecyclePlugin-unmigrated.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ import Flutter
66
import UIKit
77

88
public class MyPlugin: NSObject, FlutterPlugin {
9-
var events = [String]()
9+
public static var instance: MyPlugin?
10+
public var events = [String]()
1011

1112
public static func register(with registrar: FlutterPluginRegistrar) {
1213
let channel = FlutterMethodChannel(
1314
name: "my_plugin",
1415
binaryMessenger: registrar.messenger()
1516
)
1617
let instance = MyPlugin()
18+
MyPlugin.instance = instance
1719
registrar.addMethodCallDelegate(instance, channel: channel)
1820
registrar.addApplicationDelegate(instance)
1921
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import Flutter
6+
import FlutterPluginRegistrant
7+
import UIKit
8+
9+
class SceneDelegate: FlutterSceneDelegate {
10+
let flutterEngine = FlutterEngine(name: "my flutter engine")
11+
12+
override func scene(
13+
_ scene: UIScene,
14+
willConnectTo session: UISceneSession,
15+
options connectionOptions: UIScene.ConnectionOptions
16+
) {
17+
guard let windowScene = scene as? UIWindowScene else { return }
18+
window = UIWindow(windowScene: windowScene)
19+
20+
flutterEngine.run()
21+
GeneratedPluginRegistrant.register(with: flutterEngine)
22+
23+
// Manually register because FlutterViewController is never added to the scene hierarchy!
24+
self.registerSceneLifeCycle(with: flutterEngine, scene: windowScene)
25+
26+
let viewController = ViewController(engine: flutterEngine)
27+
window?.rootViewController = viewController
28+
window?.makeKeyAndVisible()
29+
30+
super.scene(scene, willConnectTo: session, options: connectionOptions)
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import Flutter
6+
import FlutterPluginRegistrant
7+
import UIKit
8+
9+
class SceneDelegate: FlutterSceneDelegate {
10+
let flutterEngine = FlutterEngine(name: "my flutter engine")
11+
12+
override func scene(
13+
_ scene: UIScene,
14+
willConnectTo session: UISceneSession,
15+
options connectionOptions: UIScene.ConnectionOptions
16+
) {
17+
guard let windowScene = scene as? UIWindowScene else { return }
18+
window = UIWindow(windowScene: windowScene)
19+
20+
flutterEngine.run()
21+
GeneratedPluginRegistrant.register(with: flutterEngine)
22+
23+
// Manually register using the legacy API because FlutterViewController is never added to the scene hierarchy!
24+
self.registerSceneLifeCycle(with: flutterEngine)
25+
26+
let viewController = ViewController(engine: flutterEngine)
27+
window?.rootViewController = viewController
28+
window?.makeKeyAndVisible()
29+
30+
super.scene(scene, willConnectTo: session, options: connectionOptions)
31+
}
32+
}

‎dev/integration_tests/ios_add2app_uiscene/native/SceneDelegate-FlutterSceneDelegate-MultiScene-NoStoryboard.swift‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ class SceneDelegate: FlutterSceneDelegate {
2020

2121
flutterEngine.run()
2222
GeneratedPluginRegistrant.register(with: flutterEngine)
23-
self.registerSceneLifeCycle(with: flutterEngine)
2423
let viewController = ViewController(engine: flutterEngine)
2524

2625
window?.rootViewController = viewController

‎dev/integration_tests/ios_add2app_uiscene/native/SceneDelegate-FlutterSceneDelegate-MultiScene-Storyboard.swift‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ class SceneDelegate: FlutterSceneDelegate {
1616
) {
1717
flutterEngine.run()
1818
GeneratedPluginRegistrant.register(with: flutterEngine)
19-
self.registerSceneLifeCycle(with: flutterEngine)
2019

2120
if let viewController = window?.rootViewController as? ViewController {
2221
viewController.flutterEngine = flutterEngine

‎dev/integration_tests/ios_add2app_uiscene/native/UITests-SceneEventsNoConnect-NoApplicationEvents.swift‎

Lines changed: 0 additions & 53 deletions
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import Flutter
6+
import UIKit
7+
import my_plugin
8+
9+
class ViewController: UIViewController {
10+
var flutterViewController: FlutterViewController?
11+
let label = UILabel()
12+
13+
private var flutterEngine: FlutterEngine {
14+
return (UIApplication.shared.delegate as! AppDelegate).flutterEngine
15+
}
16+
17+
override func viewDidLoad() {
18+
super.viewDidLoad()
19+
view.backgroundColor = .white
20+
21+
// Create FlutterViewController with engine, but NEVER add it to the view hierarchy or as a child VC.
22+
flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
23+
24+
setupNativeUI()
25+
}
26+
27+
private func setupNativeUI() {
28+
let button = UIButton(type: .system)
29+
button.setTitle("Get Lifecycle Events", for: .normal)
30+
button.accessibilityIdentifier = "Get Lifecycle Events"
31+
button.frame = CGRect(x: 20, y: 100, width: 250, height: 50)
32+
button.addTarget(self, action: #selector(getLifecycleEvents), for: .touchUpInside)
33+
view.addSubview(button)
34+
35+
label.frame = CGRect(x: 20, y: 160, width: 350, height: 400)
36+
label.numberOfLines = 0
37+
view.addSubview(label)
38+
}
39+
40+
@objc private func getLifecycleEvents() {
41+
if let events = MyPlugin.instance?.events.joined(separator: "\n") {
42+
self.label.text = events
43+
}
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import Flutter
6+
import UIKit
7+
import my_plugin
8+
9+
class ViewController: UIViewController {
10+
let flutterEngine: FlutterEngine
11+
var flutterViewController: FlutterViewController?
12+
let label = UILabel()
13+
14+
init(engine: FlutterEngine) {
15+
self.flutterEngine = engine
16+
super.init(nibName: nil, bundle: nil)
17+
}
18+
19+
required init?(coder: NSCoder) {
20+
fatalError("init(coder:) has not been implemented")
21+
}
22+
23+
override func viewDidLoad() {
24+
super.viewDidLoad()
25+
view.backgroundColor = .white
26+
27+
// Create FlutterViewController with engine, but NEVER add it to the view hierarchy or as a child VC.
28+
flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
29+
30+
setupNativeUI()
31+
}
32+
33+
private func setupNativeUI() {
34+
let button = UIButton(type: .system)
35+
button.setTitle("Get Lifecycle Events", for: .normal)
36+
button.accessibilityIdentifier = "Get Lifecycle Events"
37+
button.frame = CGRect(x: 20, y: 100, width: 250, height: 50)
38+
button.addTarget(self, action: #selector(getLifecycleEvents), for: .touchUpInside)
39+
view.addSubview(button)
40+
41+
label.frame = CGRect(x: 20, y: 160, width: 350, height: 400)
42+
label.numberOfLines = 0
43+
view.addSubview(label)
44+
}
45+
46+
@objc private func getLifecycleEvents() {
47+
if let events = MyPlugin.instance?.events.joined(separator: "\n") {
48+
self.label.text = events
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)