1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-08 13:58:47 +00:00

[platform_channels] adds implementation of BasicMessageChannel for iOS (#610)

This commit is contained in:
Ayush Bherwani
2020-12-15 11:45:35 +05:30
committed by GitHub
parent e940d54618
commit 64fce38501
4 changed files with 56 additions and 6 deletions

View File

@@ -45,7 +45,45 @@ import Flutter
FlutterEventChannel(name: "eventChannelDemo", binaryMessenger: flutterViewController.binaryMessenger).setStreamHandler(AccelerometerStreamHandler())
var petList : [[String:String]] = []
// A FlutterBasicMessageChannel for sending petList to Dart.
let stringCodecChannel = FlutterBasicMessageChannel(name: "stringCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterStringCodec.sharedInstance())
// Registers a MessageHandler for FlutterBasicMessageChannel to receive pet details.
FlutterBasicMessageChannel(name: "jsonMessageCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterJSONMessageCodec.sharedInstance())
.setMessageHandler{(message: Any?, reply: FlutterReply) -> Void in
petList.insert(message! as! [String: String], at: 0)
stringCodecChannel.sendMessage(self.convertPetListToJson(petList: petList))
}
// Registers a MessageHandler for FlutterBasicMessageHandler to receive indices of detail records to remove from the petList.
FlutterBasicMessageChannel(name: "binaryCodecDemo", binaryMessenger: flutterViewController.binaryMessenger, codec: FlutterBinaryCodec.sharedInstance()).setMessageHandler{
(message: Any?, reply: FlutterReply) -> Void in
guard let index = Int.init(String.init(data: message! as! Data, encoding: String.Encoding.utf8)!) else {
reply(nil)
return
}
if (index >= 0 && index < petList.count) {
petList.remove(at: index)
reply("Removed Successfully".data(using: .utf8)!)
stringCodecChannel.sendMessage(self.convertPetListToJson(petList: petList))
} else {
reply(nil)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// Function to convert petList to json string.
func convertPetListToJson(petList: [[String: String]]) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: ["petList": petList], options: .prettyPrinted) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
}