Flutter 跟 IOS 原生通信--UIKitView使用(二)
一、Flutter 主动跟iOS交互
比如flutter端向iOS原生请求获取当前手机连接wifi名字:
flutter 部分代码:
final _channel = MethodChannel("ios_channel");
_channel.invokeMethod('get_wifi_name');
如果有参数传输:
final _channel = MethodChannel("ios_channel");
var map = {
'': '',
};
_channel.invokeMethod('get_wifi_name',map);
iOS部分代码:
@interface AppDelegate ()
@property (nonatomic,strong)FlutterViewController *flutterViewController;
@property (nonatomic, strong) FlutterEventChannel *eventChannel;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.flutterViewController = [[FlutterViewController alloc]init];
self.window.rootViewController = self.flutterViewController;
FlutterMethodChannel *notifationChannel = [FlutterMethodChannel methodChannelWithName:@"ios_channel" binaryMessenger:(NSObject *)self.flutterViewController];
__weak typeof (self)weakSelf = self;
[notifationChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
if ([@"get_wifi_name" isEqualToString:call.method]) {
//如果有参数 call.arguments即从flutter端传过来的参数 map
//NSDictionary *dic = call.arguments;
NSString *wifiName = [weakSelf getWifi];
result(wifiName);
}
}];
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (NSString *)getWifi{
NSString *ssid = @"";
CFArrayRef myArray = CNCopySupportedInterfaces();
NSLog(@"myArray:%@",myArray);
if (myArray != nil) {
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo((CFStringRef)CFArrayGetValueAtIndex(myArray, 0));
if (myDict != nil) {
NSDictionary *dict = (NSDictionary *)CFBridgingRelease(myDict);
ssid = [dict valueForKey:@"SSID"];
NSLog(@"%@",dict);
}
}
return ssid;
}
二、iOS主动跟Flutter交互
比如iOS端获取监测当前手机连接wifi名字变化,同时传输flutter端
iOS 端代码:
@interface AppDelegate ()
@property (nonatomic, strong) FlutterEventChannel *eventChannel;
@property (nonatomic, copy) FlutterEventSink sink;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.flutterViewController = [[FlutterViewController alloc]init];
self.window.rootViewController = self.flutterViewController;
self.eventChannel = [FlutterEventChannel eventChannelWithName:@"ios_event_channel" binaryMessenger:(NSObject *)self.flutterViewController];
[self.eventChannel setStreamHandler:self];
[self listeningWIFIChange];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateWifi) name:@"updateWifi" object:nil];
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (void)updateWifi{
NSString *wifiName = [self getWifi];
NSLog(@"ios ---- 网络变化-----wifiName:%@",wifiName);
NSLog(@"%@",self.sink);
//通过该方法传值给flutter
if (self.sink != nil){
//当有多个值返回给flutter的时候,比如获取wifi、获取手机版本号等等,可以给dic添加个参数key区分参数,方便flutter接收的时候区分
NSDictionary *dic = {@"key":@"wifi",@"name":wifiName};
self.sink(dic);
}
}
//监听网络变化
- (void)listeningWIFIChange{
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL,onNotifyCallback, CFSTR("com.apple.system.config.network_change"), NULL,CFNotificationSuspensionBehaviorDeliverImmediately);
}
static void onNotifyCallback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo){
NSString* notifyName = (__bridge NSString *) name;
if ([notifyName isEqualToString:@"com.apple.system.config.network_change"]) {
NSLog(@"======网络变化");
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateWifi" object:nil];
} else {
NSLog(@"intercepted %@", notifyName);
}
}
#pragma mark -
// 这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
NSLog(@"onListenWithArguments");
self.sink = events;
return nil;
}
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
NSLog(@"onCancelWithArguments");
return nil;
}
Flutter 端代码:
EventChannel _eventChannel = const EventChannel("ios_event_channel");
_eventChannel
.receiveBroadcastStream("init")
.listen(_onEvent, onError: _onError);
void _onEvent(Object event) {
Map map = event;
//此处为从iOS端接收到的数据
if (map['key'] == 'wifi'){
print("wifi名字:${map['name']}");
}
}
void _onError(Object error){
print("--------------error:${error}");
}
可以在flutter端写一个单例专门处理关于数据处理的,以下发一下flutter端完整的代码:
单例代码:
class IosUtils {
static final IosUtils _managerIos = IosUtils.internal();
StreamController deviceController;
Stream deviceStream;
EventChannel _eventChannel = const EventChannel("ios_event_channel");
final _channel = MethodChannel("ios_channel");
factory IosUtils.getInstance() {
return _managerIos;
}
IosUtils.internal() {
deviceController = StreamController();
deviceStream = deviceController.stream.asBroadcastStream();
_eventChannel
.receiveBroadcastStream("init")
.listen(_onEvent, onError: _onError);
}
void _onEvent(Object event) {
Map map = event;
print("--------------map:${map}");
//添加监听
deviceController.sink.add(map);
}
void _onError(Object error){
print("--------------error:${error}");
}
void getWifiName(){
_channel.invokeMethod('get_wifi_name');
}
}
flutter页面处理代码
@override
void initState() {
super.initState();
if (Platform.isIOS){
IosUtils.getInstance().getWifiName();
IosUtils.internal().deviceStream.listen((data){
String key = data['key'];
if (map['key'] == 'wifi'){
print("wifi名字:${map['name']}");
}
});
}
}