Sub topic 7
Implementing the iOS Side in Swift
Assume you can write Dart, understand the MethodChannel API from the previous chapter, and have a working Flutter and Xcode installation. This chapter implements the iOS half of a battery plugin. The Dart side calls getBatteryLevel on the channel named battery_info.
Registering a Swift plugin
A Flutter plugin uses a Swift class to receive method calls from Dart. The class must conform to FlutterPlugin. Its register method creates a FlutterMethodChannel and connects that channel to an instance of the plugin.
The channel name and method name must exactly match the Dart code. Flutter does not automatically detect spelling differences.
import Flutter
import UIKit
public class BatteryInfoPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "battery_info",
binaryMessenger: registrar.messenger()
)
let instance = BatteryInfoPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(
_ call: FlutterMethodCall,
result: @escaping FlutterResult
) {
switch call.method {
case "getBatteryLevel":
UIDevice.current.isBatteryMonitoringEnabled = true
let level = UIDevice.current.batteryLevel
if level < 0 {
result(
FlutterError(
code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil
)
)
} else {
result(Int(level * 100))
}
default:
result(FlutterMethodNotImplemented)
}
}
}FlutterMethodCall contains the method name and any arguments sent by Dart. FlutterResult is a callback. Call it exactly once for each method call, either with a value, a FlutterError, or FlutterMethodNotImplemented.
The iOS battery API returns a Float between 0.0 and 1.0. A negative value means that the level is unknown. The implementation converts a known value to an integer percentage so it matches the Android result.
Mapping native results to Dart
The FlutterMethodChannel uses Flutter's standard message codec. Swift values such as Int, String, arrays, and dictionaries can cross the channel when the codec supports them.
When Swift returns FlutterError, Dart receives a PlatformException. The Dart API can catch that exception and convert it into a package-specific exception.
Checking the iOS implementation
Run the example application on an iOS simulator or device. The simulator may report an unavailable battery level, so test the success path on a physical device when possible. Confirm that the Dart code receives an integer from 0 to 100 and that an unavailable value becomes the expected exception.
If Swift code changes while the app is running, stop and restart the application when hot reload does not rebuild the native code. Native plugin registration happens when the Flutter engine starts.
Exercise
What should the Swift handler return when UIDevice.current.batteryLevel is negative?
Show answer
It should return a FlutterError, such as UNAVAILABLE, so Dart receives a PlatformException.