How to stream data from swift to flutter using event channel?
just call mEventSink as a function
mEventSink(data)
Use FlutterEndOfEventStream constant to signal end of stream
mEventSink(FlutterEndOfEventStream)
if you going to send error to flutter side use
mEventSink(FlutterError(code: "ERROR_CODE",
message: "Detailed message",
details: nil))
Reference to API DOC
Complete swift example
let eventChannel = FlutterEventChannel(name: "your.channel.id", binaryMessenger: messenger!)
eventChannel.setStreamHandler(SwiftStreamHandler())
....
class SwiftStreamHandler: NSObject, FlutterStreamHandler {
public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
events(true) // any generic type or more compex dictionary of [String:Any]
events(FlutterError(code: "ERROR_CODE",
message: "Detailed message",
details: nil)) // in case of errors
events(FlutterEndOfEventStream) // when stream is over
return nil
}
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
return nil
}
}
Zakria Khan
hello I am student studying software engineering(b.s) at university of malakand in kpk. am flutter developer develop dozen of app for companies and individuals and currently working as remote flutter developer from Pakistan. I join stack overflow to learn new things While Providing back the knowledge i have in the form of Answer to community Questions. thanks Have A nice Day.
Updated on December 16, 2022Comments
-
Zakria Khan over 1 year
I am making an app in which I stream data from native android and iOS side to flutter side and there I display the data in the UI.
I already did the android part. The android part is sending the data to flutter side and displays them in UI. But the problem is how to achieve same for iOS swift side.
Android code that works for me:
new EventChannel(getFlutterView(), "Eventchannelname").setStreamHandler( new EventChannel.StreamHandler() { @Override public void onListen(Object args, EventChannel.EventSink events) { Log.w(TAG, "adding listener"); mEventSink = events; // I use mEventsink.success(data) to pass the data to flutter side @Override public void onCancel(Object args) { Log.w(TAG, "cancelling listener"); } } );
How can I achieve the same in Swift native code. I googled it and did not find anything that can help me.
I want same in swift as what I did in android java: I want to capture the events in local variable and then use that where I need to send data to flutter.
-
Zakria Khan over 4 yearsI know on java side I want to same same thing in swift language.
-
Alexei Volkov over 4 yearsMy answer is about swift code check the api reference i mentioned.
-
User almost 4 yearsCan you add the declaration/instantiation of
messenger
? -
Sadeny Alpha about 3 yearsis thee anyone who has it working? am stuck the stream handler seem not to send the data