FlutterViewController.mm 20.2 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 9
#include <memory>

#include "flutter/common/threads.h"
10 11
#include "flutter/fml/platform/darwin/scoped_block.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
12
#include "flutter/shell/platform/darwin/common/buffer_conversions.h"
13
#include "flutter/shell/platform/darwin/common/platform_mac.h"
14
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
15
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
16
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
17 18
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
19
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_main_ios.h"
20
#include "flutter/shell/platform/darwin/ios/framework/Source/flutter_touch_mapper.h"
21
#include "flutter/shell/platform/darwin/ios/platform_view_ios.h"
A
Adam Barth 已提交
22
#include "lib/ftl/functional/make_copyable.h"
23
#include "lib/ftl/time/time_delta.h"
24

25 26
namespace {

27
typedef void (^PlatformMessageResponseCallback)(NSData*);
28 29 30 31 32 33 34 35 36

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 {
37
          self->callback_.get()(shell::GetNSDataFromVector(data));
38 39 40
        }));
  }

41 42 43
  void CompleteEmpty() override {
    ftl::RefPtr<PlatformMessageResponseDarwin> self(this);
    blink::Threads::Platform()->PostTask(
44
        ftl::MakeCopyable([self]() mutable { self->callback_.get()(nil); }));
45
  }
46 47

 private:
48
  explicit PlatformMessageResponseDarwin(PlatformMessageResponseCallback callback)
49
      : callback_(callback, fml::OwnershipPolicy::Retain) {}
50

51
  fml::ScopedBlock<PlatformMessageResponseCallback> callback_;
52 53 54 55
};

}  // namespace

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

59
@implementation FlutterViewController {
60
  fml::scoped_nsprotocol<FlutterDartProject*> _dartProject;
61
  UIInterfaceOrientationMask _orientationPreferences;
62
  UIStatusBarStyle _statusBarStyle;
63
  blink::ViewportMetrics _viewportMetrics;
64 65
  shell::TouchMapper _touchMapper;
  std::unique_ptr<shell::PlatformViewIOS> _platformView;
66 67 68 69 70 71
  fml::scoped_nsprotocol<FlutterPlatformPlugin*> _platformPlugin;
  fml::scoped_nsprotocol<FlutterTextInputPlugin*> _textInputPlugin;
  fml::scoped_nsprotocol<FlutterMethodChannel*> _localizationChannel;
  fml::scoped_nsprotocol<FlutterMethodChannel*> _navigationChannel;
  fml::scoped_nsprotocol<FlutterMethodChannel*> _platformChannel;
  fml::scoped_nsprotocol<FlutterMethodChannel*> _textInputChannel;
72 73
  fml::scoped_nsprotocol<FlutterBasicMessageChannel*> _lifecycleChannel;
  fml::scoped_nsprotocol<FlutterBasicMessageChannel*> _systemChannel;
74
  BOOL _initialized;
75 76
}

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

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

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

90
  if (self) {
91
    if (project == nil)
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
- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
103
  return [self initWithProject:nil nibName:nil bundle:nil];
C
Chinmay Garde 已提交
104 105
}

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

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

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

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

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

124
  _localizationChannel.reset([[FlutterMethodChannel alloc]
125
         initWithName:@"flutter/localization"
126
      binaryMessenger:self
127
                codec:[FlutterJSONMethodCodec sharedInstance]]);
128 129

  _navigationChannel.reset([[FlutterMethodChannel alloc]
130
         initWithName:@"flutter/navigation"
131
      binaryMessenger:self
132
                codec:[FlutterJSONMethodCodec sharedInstance]]);
133 134

  _platformChannel.reset([[FlutterMethodChannel alloc]
135
         initWithName:@"flutter/platform"
136
      binaryMessenger:self
137
                codec:[FlutterJSONMethodCodec sharedInstance]]);
138 139

  _textInputChannel.reset([[FlutterMethodChannel alloc]
140
         initWithName:@"flutter/textinput"
141
      binaryMessenger:self
142
                codec:[FlutterJSONMethodCodec sharedInstance]]);
143

144
  _lifecycleChannel.reset([[FlutterBasicMessageChannel alloc]
145
         initWithName:@"flutter/lifecycle"
146
      binaryMessenger:self
147
                codec:[FlutterStringCodec sharedInstance]]);
148

149
  _systemChannel.reset([[FlutterBasicMessageChannel alloc]
150
         initWithName:@"flutter/system"
151
      binaryMessenger:self
152
                codec:[FlutterJSONMessageCodec sharedInstance]]);
153

154
  _platformPlugin.reset([[FlutterPlatformPlugin alloc] init]);
155 156 157
  [_platformChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    [_platformPlugin.get() handleMethodCall:call result:result];
  }];
158

159 160
  _textInputPlugin.reset([[FlutterTextInputPlugin alloc] init]);
  _textInputPlugin.get().textInputDelegate = self;
161 162 163
  [_textInputChannel.get() setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    [_textInputPlugin.get() handleMethodCall:call result:result];
  }];
164

165
  [self setupNotificationCenterObservers];
C
Chinmay Garde 已提交
166

167
  [self connectToEngineAndLoad];
C
Chinmay Garde 已提交
168 169
}

170 171 172 173
- (void)setupNotificationCenterObservers {
  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self
             selector:@selector(onOrientationPreferencesUpdated:)
A
Adam Barth 已提交
174
                 name:@(shell::kOrientationUpdateNotificationName)
175 176
               object:nil];

177 178
  [center addObserver:self
             selector:@selector(onPreferredStatusBarStyleUpdated:)
A
Adam Barth 已提交
179
                 name:@(shell::kOverlayStyleUpdateNotificationName)
180 181
               object:nil];

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  [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];
206 207 208 209 210

  [center addObserver:self
             selector:@selector(onVoiceOverChanged:)
                 name:UIAccessibilityVoiceOverStatusChanged
               object:nil];
211 212 213 214 215

  [center addObserver:self
             selector:@selector(onMemoryWarning:)
                 name:UIApplicationDidReceiveMemoryWarningNotification
               object:nil];
C
Chinmay Garde 已提交
216 217
}

218
#pragma mark - Initializing the engine
219

220
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
221 222 223
  exit(0);
}

224
- (void)connectToEngineAndLoad {
C
Chinmay Garde 已提交
225
  TRACE_EVENT0("flutter", "connectToEngineAndLoad");
226

227
  // We ask the VM to check what it supports.
228
  const enum VMType type = Dart_IsPrecompiledRuntime() ? VMTypePrecompilation : VMTypeInterpreter;
229

A
Adam Barth 已提交
230
  [_dartProject launchInEngine:&_platformView->engine()
231 232 233
                embedderVMType:type
                        result:^(BOOL success, NSString* message) {
                          if (!success) {
234 235 236 237 238
                            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Launch Error"
                                                                            message:message
                                                                           delegate:self
                                                                  cancelButtonTitle:@"OK"
                                                                  otherButtonTitles:nil];
239 240 241 242
                            [alert show];
                            [alert release];
                          }
                        }];
243 244 245 246 247
}

#pragma mark - Loading the view

- (void)loadView {
248
  FlutterView* view = [[FlutterView alloc] init];
249

250
  self.view = view;
251
  self.view.multipleTouchEnabled = YES;
252
  self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
253

254
  [view release];
255 256 257 258 259
}

#pragma mark - Application lifecycle notifications

- (void)applicationBecameActive:(NSNotification*)notification {
260
  [_lifecycleChannel.get() sendMessage:@"AppLifecycleState.resumed"];
261 262 263
}

- (void)applicationWillResignActive:(NSNotification*)notification {
264
  [_lifecycleChannel.get() sendMessage:@"AppLifecycleState.paused"];
265 266 267 268 269 270 271 272 273 274
}

#pragma mark - Touch event handling

enum MapperPhase {
  Accessed,
  Added,
  Removed,
};

275 276
using PointerChangeMapperPhase = std::pair<blink::PointerData::Change, MapperPhase>;
static inline PointerChangeMapperPhase PointerChangePhaseFromUITouchPhase(UITouchPhase phase) {
277 278
  switch (phase) {
    case UITouchPhaseBegan:
279
      return PointerChangeMapperPhase(blink::PointerData::Change::kDown, MapperPhase::Added);
280 281 282 283
    case UITouchPhaseMoved:
    case UITouchPhaseStationary:
      // There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
      // with the same coordinates
284
      return PointerChangeMapperPhase(blink::PointerData::Change::kMove, MapperPhase::Accessed);
285
    case UITouchPhaseEnded:
286
      return PointerChangeMapperPhase(blink::PointerData::Change::kUp, MapperPhase::Removed);
287
    case UITouchPhaseCancelled:
288
      return PointerChangeMapperPhase(blink::PointerData::Change::kCancel, MapperPhase::Removed);
289 290
  }

291
  return PointerChangeMapperPhase(blink::PointerData::Change::kCancel, MapperPhase::Accessed);
292
}
C
Chinmay Garde 已提交
293 294

- (void)dispatchTouches:(NSSet*)touches phase:(UITouchPhase)phase {
295 296 297 298 299
  // 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 已提交
300
  auto eventTypePhase = PointerChangePhaseFromUITouchPhase(phase);
C
Chinmay Garde 已提交
301
  const CGFloat scale = [UIScreen mainScreen].scale;
A
Adam Barth 已提交
302
  auto packet = std::make_unique<blink::PointerDataPacket>(touches.count);
C
Chinmay Garde 已提交
303

A
Adam Barth 已提交
304
  int i = 0;
C
Chinmay Garde 已提交
305
  for (UITouch* touch in touches) {
306
    int device_id = 0;
307 308 309

    switch (eventTypePhase.second) {
      case Accessed:
310
        device_id = _touchMapper.identifierOf(touch);
311 312
        break;
      case Added:
313
        device_id = _touchMapper.registerTouch(touch);
314 315
        break;
      case Removed:
316
        device_id = _touchMapper.unregisterTouch(touch);
317 318
        break;
    }
319

320
    FTL_DCHECK(device_id != 0);
C
Chinmay Garde 已提交
321
    CGPoint windowCoordinates = [touch locationInView:nil];
322

A
Adam Barth 已提交
323 324 325
    blink::PointerData pointer_data;
    pointer_data.Clear();

326 327
    constexpr int kMicrosecondsPerSecond = 1000 * 1000;
    pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond;
A
Adam Barth 已提交
328 329
    pointer_data.change = eventTypePhase.first;
    pointer_data.kind = blink::PointerData::DeviceKind::kTouch;
330
    pointer_data.device = device_id;
A
Adam Barth 已提交
331 332 333 334 335 336
    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 已提交
337
  }
338

339 340 341 342 343
  blink::Threads::UI()->PostTask(ftl::MakeCopyable(
      [ engine = _platformView->engine().GetWeakPtr(), packet = std::move(packet) ] {
        if (engine.get())
          engine->DispatchPointerDataPacket(*packet);
      }));
C
Chinmay Garde 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
}

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

362
#pragma mark - Handle view resizing
363

364
- (void)updateViewportMetrics {
365 366 367 368 369 370 371 372
  blink::Threads::UI()->PostTask(
      [ weak_platform_view = _platformView->GetWeakPtr(), metrics = _viewportMetrics ] {
        if (!weak_platform_view) {
          return;
        }
        weak_platform_view->UpdateSurfaceSize();
        weak_platform_view->engine().SetViewportMetrics(metrics);
      });
373 374
}

375
- (CGFloat)statusBarPadding {
376
  UIScreen* screen = self.view.window.screen;
377
  CGRect statusFrame = [UIApplication sharedApplication].statusBarFrame;
378 379
  CGRect viewFrame =
      [self.view convertRect:self.view.bounds toCoordinateSpace:screen.coordinateSpace];
380 381
  CGRect intersection = CGRectIntersection(statusFrame, viewFrame);
  return CGRectIsNull(intersection) ? 0.0 : intersection.size.height;
382 383
}

384
- (void)viewDidLayoutSubviews {
385
  CGSize viewSize = self.view.bounds.size;
386 387
  CGFloat scale = [UIScreen mainScreen].scale;

388
  _viewportMetrics.device_pixel_ratio = scale;
389 390
  _viewportMetrics.physical_width = viewSize.width * scale;
  _viewportMetrics.physical_height = viewSize.height * scale;
391
  _viewportMetrics.physical_padding_top = [self statusBarPadding] * scale;
392
  [self updateViewportMetrics];
393 394
}

395
#pragma mark - Keyboard events
396

397 398
- (void)keyboardWasShown:(NSNotification*)notification {
  NSDictionary* info = [notification userInfo];
399 400
  CGFloat bottom =
      CGRectGetHeight([[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]);
401
  CGFloat scale = [UIScreen mainScreen].scale;
402 403
  _viewportMetrics.physical_padding_bottom = bottom * scale;
  [self updateViewportMetrics];
404 405
}

406
- (void)keyboardWillBeHidden:(NSNotification*)notification {
407 408
  _viewportMetrics.physical_padding_bottom = 0;
  [self updateViewportMetrics];
409 410
}

411 412 413
#pragma mark - Text input delegate

- (void)updateEditingClient:(int)client withState:(NSDictionary*)state {
414 415
  [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingState"
                              arguments:@[ @(client), state ]];
416 417
}

418 419 420 421 422 423 424
#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;

425
    NSNumber* update = info[@(shell::kOrientationUpdateNotificationKey)];
426 427 428 429 430 431 432 433 434 435 436 437

    if (update == nil) {
      return;
    }

    NSUInteger new_preferences = update.unsignedIntegerValue;

    if (new_preferences != _orientationPreferences) {
      _orientationPreferences = new_preferences;
      [UIViewController attemptRotationToDeviceOrientation];
    }
  });
438 439
}

440 441
- (BOOL)shouldAutorotate {
  return YES;
442 443
}

444 445 446 447
- (NSUInteger)supportedInterfaceOrientations {
  return _orientationPreferences;
}

448 449 450 451 452 453 454
#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.
455
  bool enabled = true;
456
#else
457
  bool enabled = UIAccessibilityIsVoiceOverRunning();
458
#endif
459
  _platformView->ToggleAccessibility(self.view, enabled);
460 461
}

462 463 464
#pragma mark - Memory Notifications

- (void)onMemoryWarning:(NSNotification*)notification {
465
  [_systemChannel.get() sendMessage:@{ @"type" : @"memoryPressure" }];
466 467
}

468 469 470 471 472 473
#pragma mark - Locale updates

- (void)onLocaleUpdated:(NSNotification*)notification {
  NSLocale* currentLocale = [NSLocale currentLocale];
  NSString* languageCode = [currentLocale objectForKey:NSLocaleLanguageCode];
  NSString* countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
474
  [_localizationChannel.get() invokeMethod:@"setLocale" arguments:@[ languageCode, countryCode ]];
475 476 477 478 479
}

#pragma mark - Surface creation and teardown updates

- (void)surfaceUpdated:(BOOL)appeared {
480
  FTL_CHECK(_platformView != nullptr);
481 482

  if (appeared) {
483
    _platformView->NotifyCreated();
484
  } else {
485
    _platformView->NotifyDestroyed();
486 487 488
  }
}

489 490
- (void)viewDidAppear:(BOOL)animated {
  [self surfaceUpdated:YES];
491 492
  [self onLocaleUpdated:nil];
  [self onVoiceOverChanged:nil];
493

494
  [super viewDidAppear:animated];
495
}
C
Chinmay Garde 已提交
496

497 498
- (void)viewWillDisappear:(BOOL)animated {
  [self surfaceUpdated:NO];
499 500

  [super viewWillDisappear:animated];
501 502
}

C
Chinmay Garde 已提交
503
- (void)dealloc {
504
  [[NSNotificationCenter defaultCenter] removeObserver:self];
505 506
  [super dealloc];
}
507

508 509 510 511 512
#pragma mark - Status Bar touch event handling

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

513
- (void)handleStatusBarTouches:(UIEvent*)event {
514 515 516 517 518 519 520 521
  // 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.
522
  for (UITouch* touch in event.allTouches) {
523 524 525 526
    if (touch.phase == UITouchPhaseBegan && touch.tapCount > 0) {
      CGPoint windowLoc = [touch locationInView:nil];
      CGPoint screenLoc = [touch.window convertPoint:windowLoc toWindow:nil];
      if (CGRectContainsPoint(statusBarFrame, screenLoc)) {
527
        NSSet* statusbarTouches = [NSSet setWithObject:touch];
528 529 530 531 532 533 534 535
        [self dispatchTouches:statusbarTouches phase:UITouchPhaseBegan];
        [self dispatchTouches:statusbarTouches phase:UITouchPhaseEnded];
        return;
      }
    }
  }
}

536 537 538 539 540 541 542 543 544 545 546
#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;

547
    NSNumber* update = info[@(shell::kOverlayStyleUpdateNotificationKey)];
548 549 550 551 552 553 554 555 556 557 558 559 560 561

    if (update == nil) {
      return;
    }

    NSInteger style = update.integerValue;

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

562
#pragma mark - FlutterBinaryMessenger
563

564 565
- (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
  [self sendOnChannel:channel message:message binaryReply:nil];
566 567
}

568 569 570
- (void)sendOnChannel:(NSString*)channel
              message:(NSData*)message
          binaryReply:(FlutterBinaryReply)callback {
571
  NSAssert(channel, @"The channel must not be null");
572 573 574 575 576 577 578 579 580
  ftl::RefPtr<PlatformMessageResponseDarwin> response =
      (callback == nil) ? nullptr
                        : ftl::MakeRefCounted<PlatformMessageResponseDarwin>(^(NSData* reply) {
                            callback(reply);
                          });
  ftl::RefPtr<blink::PlatformMessage> platformMessage =
      (message == nil) ? ftl::MakeRefCounted<blink::PlatformMessage>(channel.UTF8String, response)
                       : ftl::MakeRefCounted<blink::PlatformMessage>(
                             channel.UTF8String, shell::GetVectorFromNSData(message), response);
581
  _platformView->DispatchPlatformMessage(platformMessage);
582 583
}

584 585 586
- (void)setMessageHandlerOnChannel:(NSString*)channel
              binaryMessageHandler:(FlutterBinaryMessageHandler)handler {
  NSAssert(channel, @"The channel must not be null");
587
  _platformView->platform_message_router().SetMessageHandler(channel.UTF8String, handler);
588
}
C
Chinmay Garde 已提交
589
@end