Flutter 原生通信 (四) - iOS 通知 Flutter

文章目录

原生通信系列





本篇主要介绍如何在 iOS 中发布广播,然后在 dart 端进行订阅

oc

先来查看 OC 篇

 1#import "BattlePowerPlugin.h"
 2#import <Foundation/NSTimer.h>
 3
 4@implementation BattlePowerPlugin
 5
 6+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
 7    //  ...
 8
 9    [self registerPostTimerWithRegistrar:registrar];
10}
11
12+(void) registerPostTimerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar{
13    FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:@"run_time" binaryMessenger:[registrar messenger]];
14
15    long start = [self getNow];
16
17    [NSTimer scheduledTimerWithTimeInterval:5 repeats:true block:^(NSTimer * _Nonnull timer) {
18        long run = [self getNow] - start;
19        [channel sendMessage:[NSNumber numberWithLong:run]];
20
21        if (run > 100){
22            [timer invalidate];
23        }
24    }];
25}
26
27+(long)getNow{
28    NSDate *date = [NSDate date];
29    long timeStamp = [date timeIntervalSince1970];
30    return timeStamp;
31}
32
33//...
34
35@end

间隔 5 秒通过 sendMessage 发送一条消息

dart

再来看 dart 代码,这里和系列文章第二篇一致

 1import 'dart:async';
 2
 3import 'package:flutter/services.dart';
 4
 5class BattlePower {
 6  // ...
 7
 8  static const BasicMessageChannel<dynamic> runTimer = const BasicMessageChannel("run_time", StandardMessageCodec());
 9
10  static void initMessageHandler() {
11    print("initMessageHandler");
12    runTimer.setMessageHandler((dynamic value) {
13      // 接收到的时间
14      int time = value;
15      print("value = $time");
16    });
17  }
18}

这里使用BasicMessageChannel 接收回调

看看  运行结果,这里和 android 不一样, ios 的时间戳是 double 形式, 小数点左边是秒, 我这里进行了强转,所以获取到的时间就只有秒

图片


好了 插件入门篇到这里就结束了,希望大家多多为开源做出贡献,也希望大家的 flutter 开发之路越走越宽