ios - 如何在 Swift 本机代码中从 Flutter 调用参数?
问题描述
我正在尝试在 Flutter 中使用 PlatformViews 在我的 Flutter 应用程序中本地显示 Swift 代码,但是我的应用程序因当前代码而崩溃。
这是我的 AppDelegate 目前我正在调用我的方法通道:
import Foundation
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, TJPlacementDelegate {
var p = TJPlacement()
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let channelName = "NativeView"
let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
let methodChannel = FlutterMethodChannel(name: channelName, binaryMessenger: rootViewController as! FlutterBinaryMessenger)
methodChannel.setMethodCallHandler {(call: FlutterMethodCall, result: FlutterResult) -> Void in
if (call.method == "setDebugEnabled") {
let isDebug = call.arguments as! Bool
Tapjoy.setDebugEnabled(isDebug)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
这是我的原生代码的 Dart 实现:
import 'package:flutter/material.dart';
import 'tapjoy.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
callTapjoy();
super.initState();
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: UiKitView(viewType: 'NativeView'),
),
);
}
void callTapjoy() {
Tapjoy.setDebugEnabled(true);
}
}
//My code in tapjoy.dart
class Tapjoy {
static const MethodChannel _channel = const MethodChannel('NativeView');
static void setDebugEnabled(bool isDebug) {
_channel.invokeMethod('setDebugEnabled', {"isDebug": isDebug});
}
}
我的应用程序崩溃并在调试控制台中显示错误:
Could not cast value of type '__NSDictionaryM' (0x7fff87a61d78) to 'NSNumber' (0x7fff87b1eb08).
2020-04-29 16:56:42.985269+0530 Runner[18484:224162] Could not cast value of type '__NSDictionaryM' (0x7fff87a61d78) to 'NSNumber' (0x7fff87b1eb08).
解决方案
您正在将 a Map
from Dart 传递给 native: {"isDebug": isDebug}
,因此您需要在 Swift 端从地图/字典中提取参数。
if let args = call.arguments as? Dictionary<String, Any>,
let isDebug = args["isDebug"] as? Bool {
// please check the "as" above - wasn't able to test
// handle the method
result(nil)
} else {
result(FlutterError.init(code: "errorSetDebug", message: "data or format error", details: nil))
}
或者,只需从 Dart 端传递布尔值,而无需先将其放入地图中。
_channel.invokeMethod('setDebugEnabled', isDebug);
推荐阅读
- javascript - Kendo UI ToolTip on Icon
- c# - 创建 LINQ 查询对象
- c - C:为什么静态变量不能像全局变量一样在外部链接
- bash - 使用 tee 记录每个异常以重新生成 bash 脚本
- gstreamer - cerbero 无法在 ubuntu 18.04 上构建 gstreamer
- mysql - 具有 64 GB Ram 的 Mysql Tuning Server 消耗 50% 的 CPU
- php - PHP列出每一天的日期,从今天的日期开始,到下个月的第15天结束
- javascript - Jquery 或 Javascript 字符串运算符添加值
- opencv - opencv sRGB 到 RGB 转换
- c++ - 无法从 glReadpixels 创建 HBITMAP