gpt4 book ai didi

ios - 如何在 Swift native 代码中从 Flutter 调用参数?

转载 作者:行者123 更新时间:2023-12-01 16:05:38 26 4
gpt4 key购买 nike

我正在尝试使用 Flutter 中的 PlatformViews 在我的 Flutter 应用程序中本地显示 Swift 代码,但是我的应用程序因我当前的代码而崩溃。

这是我目前正在调用我的方法 channel 的 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)
}
}

这是我对 native 代码的 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).

enter image description here

最佳答案

您正在将 Map 从 Dart 传递给 native : {"isDebug": isDebug} ,因此您需要从 Swift 端的 map /字典中提取参数。

  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 端传递 bool 值,而无需先将其放入映射中。
_channel.invokeMethod('setDebugEnabled', isDebug);

关于ios - 如何在 Swift native 代码中从 Flutter 调用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61489762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com