FlutterViewController.mm 20.3 KB
Newer Older
1
// Copyright 2016 The Chromium Authors. All rights reserved.
C
Chinmay Garde 已提交
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
C
Chinmay Garde 已提交
6

A
Adam Barth 已提交
7 8
#include <memory>

9 10 11
#include "base/mac/scoped_block.h"
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
A
Adam Barth 已提交
12
#include "flutter/common/threads.h"
13 14 15
#include "flutter/shell/gpu/gpu_rasterizer.h"
#include "flutter/shell/gpu/gpu_surface_gl.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
16
#include "flutter/shell/platform/darwin/common/string_conversions.h"
17
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
18
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
19 20
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
21
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_main_ios.h"
22
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
23
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
A
Adam Barth 已提交
24
#include "lib/ftl/functional/make_copyable.h"
25
#include "lib/ftl/time/time_delta.h"
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
namespace {

typedef void (^PlatformMessageResponseCallback)(NSString*);

class PlatformMessageResponseDarwin : public blink::PlatformMessageResponse {
  FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseDarwin);

 public:
  void Complete(std::vector<uint8_t> data) override {
    ftl::RefPtr<PlatformMessageResponseDarwin> self(this);
    blink::Threads::Platform()->PostTask(
        ftl::MakeCopyable([ self, data = std::move(data) ]() mutable {
          self->callback_.get()(shell::GetNSStringFromVector(data));
        }));
  }

  void CompleteWithError() override { Complete(std::vector<uint8_t>()); }

 private:
46 47
  explicit PlatformMessageResponseDarwin(
      PlatformMessageResponseCallback callback)
48 49 50 51 52 53 54
      : callback_(callback, base::scoped_policy::RETAIN) {}

  base::mac::ScopedBlock<PlatformMessageResponseCallback> callback_;
};

}  // namespace

55 56
@interface FlutterViewController ()<UIAlertViewDelegate,
                                    FlutterTextInputDelegate>
57 58
@end

59
void FlutterInit(int argc, const char* argv[]) {
60 61 62
  // Deprecated. To be removed.
}

63
@implementation FlutterViewController {
64
  base::scoped_nsprotocol<FlutterDartProject*> _dartProject;
65
  UIInterfaceOrientationMask _orientationPreferences;
66
  UIStatusBarStyle _statusBarStyle;
67
  blink::ViewportMetrics _viewportMetrics;
68 69
  shell::TouchMapper _touchMapper;
  std::unique_ptr<shell::PlatformViewIOS> _platformView;
70
  base::scoped_nsprotocol<FlutterPlatformPlugin*> _platformPlugin;
71
  base::scoped_nsprotocol<FlutterTextInputPlugin*> _textInputPlugin;
72

73
  BOOL _initialized;
74 75
}

76 77 78 79 80 81
+ (void)initialize {
  if (self == [FlutterViewController class]) {
    shell::FlutterMain();
  }
}

82 83
#pragma mark - Manage and override all designated initializers

84 85 86 87
- (instancetype)initWithProject:(FlutterDartProject*)project
                        nibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
88

89
  if (self) {
90
    if (project == nil)
91 92
      _dartProject.reset(
          [[FlutterDartProject alloc] initFromDefaultSourceForConfiguration]);
93 94
    else
      _dartProject.reset([project retain]);
95 96

    [self performCommonViewControllerInitialization];
97
  }
98

99
  return self;
C
Chinmay Garde 已提交
100 101
}

102 103
- (instancetype)initWithNibName:(NSString*)nibNameOrNil
                         bundle:(NSBundle*)nibBundleOrNil {
104
  return [self initWithProject:nil nibName:nil bundle:nil];
C
Chinmay Garde 已提交
105 106
}

107
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
108
  return [self initWithProject:nil nibName:nil bundle:nil];
109 110
}

111
#pragma mark - Common view controller initialization tasks
C
Chinmay Garde 已提交
112

113
- (void)performCommonViewControllerInitialization {
114
  if (_initialized)
115
    return;
116

117
  _initialized = YES;
C
Chinmay Garde 已提交
118

119
  _orientationPreferences = UIInterfaceOrientationMaskAll;
120
  _statusBarStyle = UIStatusBarStyleDefault;
A
Adam Barth 已提交
121
  _platformView = std::make_unique<shell::PlatformViewIOS>(
122 123
      reinterpret_cast<CAEAGLLayer*>(self.view.layer));
  _platformView->SetupResourceContextOnIOThread();
C
Chinmay Garde 已提交
124

125 126 127
  _platformPlugin.reset([[FlutterPlatformPlugin alloc] init]);
  [self addMessageListener:_platformPlugin.get()];

128 129 130 131
  _textInputPlugin.reset([[FlutterTextInputPlugin alloc] init]);
  _textInputPlugin.get().textInputDelegate = self;
  [self addMessageListener:_textInputPlugin.get()];

132
  [self setupNotificationCenterObservers];
C
Chinmay Garde 已提交
133

134
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
135 136
}

137 138 139 140
- (void)setupNotificationCenterObservers {
  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self
             selector:@selector(onOrientationPreferencesUpdated:)
A
Adam Barth 已提交
141
                 name:@(shell::kOrientationUpdateNotificationName)
142 143
               object:nil];

144 145
  [center addObserver:self
             selector:@selector(onPreferredStatusBarStyleUpdated:)
A
Adam Barth 已提交
146
                 name:@(shell::kOverlayStyleUpdateNotificationName)
147 148
               object:nil];

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  [center addObserver:self
             selector:@selector(applicationBecameActive:)
                 name:UIApplicationDidBecomeActiveNotification
               object:nil];

  [center addObserver:self
             selector:@selector(applicationWillResignActive:)
                 name:UIApplicationWillResignActiveNotification
               object:nil];

  [center addObserver:self
             selector:@selector(keyboardWasShown:)
                 name:UIKeyboardDidShowNotification
               object:nil];

  [center addObserver:self
             selector:@selector(keyboardWillBeHidden:)
                 name:UIKeyboardWillHideNotification
               object:nil];

  [center addObserver:self
             selector:@selector(onLocaleUpdated:)
                 name:NSCurrentLocaleDidChangeNotification
               object:nil];
173 174 175 176 177

  [center addObserver:self
             selector:@selector(onVoiceOverChanged:)
                 name:UIAccessibilityVoiceOverStatusChanged
               object:nil];
C
Chinmay Garde 已提交
178 179
}

180
#pragma mark - Initializing the engine
181

182
- (void)alertView:(UIAlertView*)alertView
183
    clickedButtonAtIndex:(NSInteger)buttonIndex {
184 185 186
  exit(0);
}

187
- (void)connectToEngineAndLoad {
C
Chinmay Garde 已提交
188
  TRACE_EVENT0("flutter", "connectToEngineAndLoad");
189

190
  // We ask the VM to check what it supports.
191 192
  const enum VMType type =
      Dart_IsPrecompiledRuntime() ? VMTypePrecompilation : VMTypeInterpreter;
193

A
Adam Barth 已提交
194
  [_dartProject launchInEngine:&_platformView->engine()
195 196 197 198 199 200
                embedderVMType:type
                        result:^(BOOL success, NSString* message) {
                          if (!success) {
                            UIAlertView* alert = [[UIAlertView alloc]
                                    initWithTitle:@"Launch Error"
                                          message:message
201
                                         delegate:self
202 203 204 205 206 207
                                cancelButtonTitle:@"OK"
                                otherButtonTitles:nil];
                            [alert show];
                            [alert release];
                          }
                        }];
208 209 210 211 212
}

#pragma mark - Loading the view

- (void)loadView {
213
  FlutterView* view = [[FlutterView alloc] init];
214

215
  self.view = view;
216 217 218 219
  self.view.multipleTouchEnabled = YES;
  self.view.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

220
  [view release];
221 222 223 224 225
}

#pragma mark - Application lifecycle notifications

- (void)applicationBecameActive:(NSNotification*)notification {
226 227
  [self sendString:@"AppLifecycleState.resumed"
      withMessageName:@"flutter/lifecycle"];
228 229 230
}

- (void)applicationWillResignActive:(NSNotification*)notification {
231 232
  [self sendString:@"AppLifecycleState.paused"
      withMessageName:@"flutter/lifecycle"];
233 234 235 236 237 238 239 240 241 242
}

#pragma mark - Touch event handling

enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

243 244
using PointerChangeMapperPhase =
    std::pair<blink::PointerData::Change, MapperPhase>;
A
Adam Barth 已提交
245
static inline PointerChangeMapperPhase PointerChangePhaseFromUITouchPhase(
246 247 248
    UITouchPhase phase) {
  switch (phase) {
    case UITouchPhaseBegan:
A
Adam Barth 已提交
249 250
      return PointerChangeMapperPhase(blink::PointerData::Change::kDown,
                                      MapperPhase::Added);
251 252 253 254
    case UITouchPhaseMoved:
    case UITouchPhaseStationary:
      // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
      // with the same coordinates
A
Adam Barth 已提交
255 256
      return PointerChangeMapperPhase(blink::PointerData::Change::kMove,
                                      MapperPhase::Accessed);
257
    case UITouchPhaseEnded:
A
Adam Barth 已提交
258 259
      return PointerChangeMapperPhase(blink::PointerData::Change::kUp,
                                      MapperPhase::Removed);
260
    case UITouchPhaseCancelled:
A
Adam Barth 已提交
261 262
      return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                      MapperPhase::Removed);
263 264
  }

A
Adam Barth 已提交
265 266
  return PointerChangeMapperPhase(blink::PointerData::Change::kCancel,
                                  MapperPhase::Accessed);
267
}
C
Chinmay Garde 已提交
268 269

- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
270 271 272 273 274
  // Note: we cannot rely on touch.phase, since in some cases, e.g.,
  // handleStatusBarTouches, we synthesize touches from existing events.
  //
  // TODO(cbracken) consider creating out own class with the touch fields we
  // need.
A
Adam Barth 已提交
275
  auto eventTypePhase = PointerChangePhaseFromUITouchPhase(phase);
C
Chinmay Garde 已提交
276
  const CGFloat scale = [UIScreen mainScreen].scale;
A
Adam Barth 已提交
277
  auto packet = std::make_unique<blink::PointerDataPacket>(touches.count);
C
Chinmay Garde 已提交
278

A
Adam Barth 已提交
279
  int i = 0;
C
Chinmay Garde 已提交
280
  for (UITouch* touch in touches) {
281
    int device_id = 0;
282 283 284

    switch (eventTypePhase.second) {
      case Accessed:
285
        device_id = _touchMapper.identifierOf(touch);
286 287
        break;
      case Added:
288
        device_id = _touchMapper.registerTouch(touch);
289 290
        break;
      case Removed:
291
        device_id = _touchMapper.unregisterTouch(touch);
292 293
        break;
    }
294

295
    DCHECK(device_id != 0);
C
Chinmay Garde 已提交
296
    CGPoint windowCoordinates = [touch locationInView:nil];
297

A
Adam Barth 已提交
298 299 300
    blink::PointerData pointer_data;
    pointer_data.Clear();

301 302
    constexpr int kMicrosecondsPerSecond = 1000 * 1000;
    pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond;
A
Adam Barth 已提交
303 304
    pointer_data.change = eventTypePhase.first;
    pointer_data.kind = blink::PointerData::DeviceKind::kTouch;
305
    pointer_data.device = device_id;
A
Adam Barth 已提交
306 307 308 309 310 311
    pointer_data.physical_x = windowCoordinates.x * scale;
    pointer_data.physical_y = windowCoordinates.y * scale;
    pointer_data.pressure = 1.0;
    pointer_data.pressure_max = 1.0;

    packet->SetPointerData(i++, pointer_data);
C
Chinmay Garde 已提交
312
  }
313

A
Adam Barth 已提交
314
  blink::Threads::UI()->PostTask(ftl::MakeCopyable([
315 316 317 318 319
    engine = _platformView->engine().GetWeakPtr(), packet = std::move(packet)
  ] {
    if (engine.get())
      engine->DispatchPointerDataPacket(*packet);
  }));
C
Chinmay Garde 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseBegan];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseMoved];
}

- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseEnded];
}

- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
  [self dispatchTouches:touches phase:UITouchPhaseCancelled];
}

338
#pragma mark - Handle view resizing
339

340 341
- (void)updateViewportMetrics {
  blink::Threads::UI()->PostTask([
342
    weak_platform_view = _platformView->GetWeakPtr(), metrics = _viewportMetrics
343
  ] {
344 345 346 347 348
    if (!weak_platform_view) {
      return;
    }
    weak_platform_view->UpdateSurfaceSize();
    weak_platform_view->engine().SetViewportMetrics(metrics);
349 350 351
  });
}

352
- (bool)isWindowFullscreen {
353
  UIWindow* window = self.view.window;
354 355 356 357 358 359 360 361 362 363 364 365 366 367
  return CGRectEqualToRect(window.frame, window.screen.bounds);
}

- (CGFloat)statusBarPadding {
  // If we're a child of a containing view, let the container apply padding.
  if (self.parentViewController != nil) {
    return 0.0;
  }

  // If not fullscreen, assume we don't want padding.
  if (![self isWindowFullscreen]) {
    return 0.0;
  }

368
  UIScreen* screen = self.view.window.screen;
369 370 371
  CGRect statusFrame = [UIApplication sharedApplication].statusBarFrame;
  CGRect viewFrame = [self.view convertRect:self.view.bounds
                          toCoordinateSpace:screen.coordinateSpace];
372 373
  CGFloat padding =
      statusFrame.origin.y + statusFrame.size.height - viewFrame.origin.y;
374 375 376
  return MAX(padding, 0.0);
}

377
- (void)viewDidLayoutSubviews {
378
  CGSize viewSize = self.view.bounds.size;
379 380
  CGFloat scale = [UIScreen mainScreen].scale;

381
  _viewportMetrics.device_pixel_ratio = scale;
382 383
  _viewportMetrics.physical_width = viewSize.width * scale;
  _viewportMetrics.physical_height = viewSize.height * scale;
384
  _viewportMetrics.physical_padding_top = [self statusBarPadding] * scale;
385
  [self updateViewportMetrics];
386 387
}

388
#pragma mark - Keyboard events
389

390 391 392 393 394
- (void)keyboardWasShown:(NSNotification*)notification {
  NSDictionary* info = [notification userInfo];
  CGFloat bottom = CGRectGetHeight(
      [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]);
  CGFloat scale = [UIScreen mainScreen].scale;
395 396
  _viewportMetrics.physical_padding_bottom = bottom * scale;
  [self updateViewportMetrics];
397 398
}

399
- (void)keyboardWillBeHidden:(NSNotification*)notification {
400 401
  _viewportMetrics.physical_padding_bottom = 0;
  [self updateViewportMetrics];
402 403
}

404 405 406
#pragma mark - Text input delegate

- (void)updateEditingClient:(int)client withState:(NSDictionary*)state {
407 408 409 410 411
  NSDictionary* message = @{
    @"method" : @"TextInputClient.updateEditingState",
    @"args" : @[ @(client), state ],
  };
  [self sendJSON:message withMessageName:@"flutter/textinputclient"];
412 413
}

414 415 416 417 418 419 420
#pragma mark - Orientation updates

- (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
  // Notifications may not be on the iOS UI thread
  dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary* info = notification.userInfo;

421
    NSNumber* update = info[@(shell::kOrientationUpdateNotificationKey)];
422 423 424 425 426 427 428 429 430 431 432 433

    if (update == nil) {
      return;
    }

    NSUInteger new_preferences = update.unsignedIntegerValue;

    if (new_preferences != _orientationPreferences) {
      _orientationPreferences = new_preferences;
      [UIViewController attemptRotationToDeviceOrientation];
    }
  });
434 435
}

436 437
- (BOOL)shouldAutorotate {
  return YES;
438 439
}

440 441 442 443
- (NSUInteger)supportedInterfaceOrientations {
  return _orientationPreferences;
}

444 445 446 447 448 449 450
#pragma mark - Accessibility

- (void)onVoiceOverChanged:(NSNotification*)notification {
#if TARGET_OS_SIMULATOR
  // There doesn't appear to be any way to determine whether the accessibility
  // inspector is enabled on the simulator. We conservatively always turn on the
  // accessibility bridge in the simulator.
451
  bool enabled = true;
452
#else
453
  bool enabled = UIAccessibilityIsVoiceOverRunning();
454
#endif
455
  _platformView->ToggleAccessibility(self.view, enabled);
456 457
}

458 459 460 461 462 463
#pragma mark - Locale updates

- (void)onLocaleUpdated:(NSNotification*)notification {
  NSLocale* currentLocale = [NSLocale currentLocale];
  NSString* languageCode = [currentLocale objectForKey:NSLocaleLanguageCode];
  NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
464 465 466 467
  NSDictionary* message =
      @{ @"method" : @"setLocale",
         @"args" : @[ languageCode, countryCode ] };
  [self sendJSON:message withMessageName:@"flutter/localization"];
468 469 470 471 472
}

#pragma mark - Surface creation and teardown updates

- (void)surfaceUpdated:(BOOL)appeared {
473
  CHECK(_platformView != nullptr);
474 475

  if (appeared) {
476 477
    _platformView->NotifyCreated(
        std::make_unique<shell::GPUSurfaceGL>(_platformView.get()));
478
  } else {
479
    _platformView->NotifyDestroyed();
480 481 482
  }
}

483 484
- (void)viewDidAppear:(BOOL)animated {
  [self surfaceUpdated:YES];
485 486
  [self onLocaleUpdated:nil];
  [self onVoiceOverChanged:nil];
487

488
  [super viewDidAppear:animated];
489
}
C
Chinmay Garde 已提交
490

491 492
- (void)viewWillDisappear:(BOOL)animated {
  [self surfaceUpdated:NO];
493 494

  [super viewWillDisappear:animated];
495 496
}

C
Chinmay Garde 已提交
497
- (void)dealloc {
498
  [[NSNotificationCenter defaultCenter] removeObserver:self];
499 500
  [super dealloc];
}
501

502 503 504 505 506
#pragma mark - Status Bar touch event handling

// Standard iOS status bar height in pixels.
constexpr CGFloat kStandardStatusBarHeight = 20.0;

507
- (void)handleStatusBarTouches:(UIEvent*)event {
508 509 510 511 512 513 514 515
  // If the status bar is double-height, don't handle status bar taps. iOS
  // should open the app associated with the status bar.
  CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
  if (statusBarFrame.size.height != kStandardStatusBarHeight) {
    return;
  }

  // If we detect a touch in the status bar, synthesize a fake touch begin/end.
516
  for (UITouch* touch in event.allTouches) {
517 518 519 520
    if (touch.phase == UITouchPhaseBegan && touch.tapCount > 0) {
      CGPoint windowLoc = [touch locationInView:nil];
      CGPoint screenLoc = [touch.window convertPoint:windowLoc toWindow:nil];
      if (CGRectContainsPoint(statusBarFrame, screenLoc)) {
521
        NSSet* statusbarTouches = [NSSet setWithObject:touch];
522 523 524 525 526 527 528 529
        [self dispatchTouches:statusbarTouches phase:UITouchPhaseBegan];
        [self dispatchTouches:statusbarTouches phase:UITouchPhaseEnded];
        return;
      }
    }
  }
}

530 531 532 533 534 535 536 537 538 539 540
#pragma mark - Status bar style

- (UIStatusBarStyle)preferredStatusBarStyle {
  return _statusBarStyle;
}

- (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
  // Notifications may not be on the iOS UI thread
  dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary* info = notification.userInfo;

541
    NSNumber* update = info[@(shell::kOverlayStyleUpdateNotificationKey)];
542 543 544 545 546 547 548 549 550 551 552 553 554 555

    if (update == nil) {
      return;
    }

    NSInteger style = update.integerValue;

    if (style != _statusBarStyle) {
      _statusBarStyle = static_cast<UIStatusBarStyle>(style);
      [self setNeedsStatusBarAppearanceUpdate];
    }
  });
}

556
#pragma mark - Application Messages
557

558
- (void)sendString:(NSString*)message withMessageName:(NSString*)channel {
559
  NSAssert(message, @"The message must not be null");
560 561 562
  NSAssert(channel, @"The channel must not be null");
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
563
          channel.UTF8String, shell::GetVectorFromNSString(message), nullptr));
564 565 566
}

- (void)sendString:(NSString*)message
567
    withMessageName:(NSString*)channel
568
           callback:(void (^)(NSString*))callback {
569
  NSAssert(message, @"The message must not be null");
570
  NSAssert(channel, @"The channel must not be null");
571
  NSAssert(callback, @"The callback must not be null");
572 573
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
574
          channel.UTF8String, shell::GetVectorFromNSString(message),
575
          ftl::MakeRefCounted<PlatformMessageResponseDarwin>(callback)));
576 577
}

578
- (void)sendJSON:(NSDictionary*)message withMessageName:(NSString*)channel {
579 580
  NSData* data =
      [NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
581 582
  if (!data)
    return;
583
  const uint8_t* bytes = static_cast<const uint8_t*>(data.bytes);
584 585
  _platformView->DispatchPlatformMessage(
      ftl::MakeRefCounted<blink::PlatformMessage>(
586
          channel.UTF8String, std::vector<uint8_t>(bytes, bytes + data.length),
587 588 589
          nullptr));
}

590
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener {
591
  NSAssert(listener, @"The listener must not be null");
592 593
  NSString* channel = listener.messageName;
  NSAssert(channel, @"The channel must not be null");
594 595
  _platformView->platform_message_router().SetMessageListener(
      channel.UTF8String, listener);
596 597
}

598
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener {
599
  NSAssert(listener, @"The listener must not be null");
600 601
  NSString* channel = listener.messageName;
  NSAssert(channel, @"The channel must not be null");
602 603
  _platformView->platform_message_router().SetMessageListener(
      channel.UTF8String, nil);
604 605
}

606 607
- (void)addAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
608 609 610
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
611
  _platformView->platform_message_router().SetAsyncMessageListener(
612
      messageName.UTF8String, listener);
613 614
}

615 616
- (void)removeAsyncMessageListener:
    (NSObject<FlutterAsyncMessageListener>*)listener {
617 618 619
  NSAssert(listener, @"The listener must not be null");
  NSString* messageName = listener.messageName;
  NSAssert(messageName, @"The messageName must not be null");
620
  _platformView->platform_message_router().SetAsyncMessageListener(
621
      messageName.UTF8String, nil);
C
Chinmay Garde 已提交
622 623 624
}

@end