Sub topic 7
Implementing the iOS side in Swift
This chapter assumes you have read the earlier chapters on pubspec.yaml plugin declarations, platform channels, and the Dart API. You should be able to read basic Swift. You also need Xcode installed and a Flutter toolchain that can build the example app for iOS.
By the end you will have a BatteryInfoPlugin class in Swift that answers getBatteryLevel calls from Dart. You will also know where the iOS side usually goes wrong.
Where the Swift code lives
The flutter create --template=plugin command generates the iOS code under the plugin's ios/ folder. The exact layout depends on your Flutter version.
- Projects generated for CocoaPods have
ios/battery_info.podspecandios/Classes/BatteryInfoPlugin.swift. - Newer Flutter versions can also generate a Swift Package Manager layout, with sources under
ios/battery_info/Sources/battery_info/.
The Swift class is the same in both layouts. Only the file path and the manifest differ.
The class name must match pluginClass under flutter.plugin.platforms.ios in pubspec.yaml. When an app builds, Flutter generates a file called GeneratedPluginRegistrant that calls register(with:) on every plugin class it finds. If the name in pubspec.yaml is misspelled, the build succeeds, but the call from Dart fails at run time with MissingPluginException.
The podspec
For CocoaPods, the podspec tells Xcode which files to compile and which frameworks to link.
Pod::Spec.new do |s|
s.name = 'battery_info'
s.version = '0.0.1'
s.summary = 'Reads the battery level on Android and iOS.'
s.description = 'Reads the battery level on Android and iOS.'
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.platform = :ios, '12.0'
s.swift_version = '5.0'
ends.dependency 'Flutter' is what makes import Flutter work. source_files must cover the folder where your Swift files live. If you move the file and don't update this glob, the class is not compiled, and you get the same MissingPluginException as above.
How a call reaches Swift
The diagram shows the path of one getBatteryLevel call.
The plugin class
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)
}
}
}The pieces
FlutterPluginis the protocol that requires the staticregister(with:)method. Flutter calls it once per engine.FlutterPluginRegistrargives you the binary messenger for creating channels. It also lets you reach other registration features, such as asset lookup.FlutterMethodChannel(name:binaryMessenger:)must use exactly the same name string as the DartMethodChanneland the Kotlin channel. A mismatch causes aMissingPluginException, not a compile error.addMethodCallDelegate(_:channel:)connects the channel tohandle(_:result:)on your instance. It keeps a strong reference to the instance, so you don't need to store it yourself.FlutterMethodNotImplementedis the Swift equivalent of Kotlin'sresult.notImplemented(). Dart sees it as aMissingPluginException.
The result callback
result is a closure that you must call exactly once for each call. The three ways to answer are:
| What you pass | What Dart receives |
|---|---|
| Any supported value, or `nil` | The value returned by `invokeMethod`, or `null` |
| `FlutterError(code:message:details:)` | A `PlatformException` with the same fields |
| `FlutterMethodNotImplemented` | A `MissingPluginException` |
If you never call result, the Dart Future never completes. Check every guard and early return in your handler for a path that skips the call. If you call result twice, the second call is ignored in release builds and logs an error in debug builds.
Types that cross the channel
The standard codec converts Dart values to Foundation types on the Swift side.
| Dart | Swift |
|---|---|
| `null` | `nil` |
| `bool` | `NSNumber` (read it with `as? Bool`) |
| `int` | `NSNumber` (read it with `as? Int`) |
| `double` | `NSNumber` (read it with `as? Double`) |
| `String` | `String` |
| `Uint8List` | `FlutterStandardTypedData` |
| `List` | `Array` of `Any?` |
| `Map` | `Dictionary` with `AnyHashable` keys |
Always read arguments with a conditional cast and handle the failure. A force cast crashes the whole app if Dart sends the wrong type. This handler reads a map and returns an error when the arguments are malformed:
import Flutter
import UIKit
public class EchoPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "echo", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(EchoPlugin(), channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "repeat":
guard let args = call.arguments as? [String: Any],
let text = args["text"] as? String,
let count = args["count"] as? Int else {
result(FlutterError(code: "BAD_ARGS", message: "Expected text and count.", details: nil))
return
}
result(String(repeating: text, count: max(count, 0)))
default:
result(FlutterMethodNotImplemented)
}
}
}Gotchas specific to iOS
The simulator reports -1
UIDevice.batteryLevel returns -1.0 when monitoring is off or the level is unknown. The iOS Simulator has no battery, so it always returns -1.0. This is why the handler returns UNAVAILABLE. Test the success path on a real iPhone. Test the error path on the simulator, where it is easy to trigger.
Truncation versus rounding
Int(level * 100) drops the fraction. batteryLevel is a Float, and a value such as 0.42 can come out as 41.999996 after multiplication. That produces 41. Use Int((level * 100).rounded()) if you want the nearest percentage.
Threading
Flutter calls handle on the platform (main) thread. UIKit properties like UIDevice are safe to read there. Long-running work blocks the UI, so move it to a background queue. When you finish, call result from the main thread. A later chapter covers this in detail.
Calls before the engine is ready
Don't read from UIApplication or the app delegate in register(with:). Plugins register while the app is still launching. Do that work lazily, inside handle.
Swift visibility
FlutterPlugin is an Objective-C protocol, so the class must be public and inherit from NSObject. Private or internal classes cause linker or registration errors in the generated registrant.
Checking your work
- Build the example app for an iOS simulator with
flutter run. Confirm the call produces aPlatformExceptionwith codeUNAVAILABLE, which your Dart layer wraps inBatteryInfoException. - Run the example on a physical iPhone. Confirm the displayed percentage matches the level shown in Control Center.
- Temporarily change the Swift channel name to
battery_info_x. Confirm that Dart now reportsMissingPluginException, then change it back.
Exercise
On a real iPhone your handler returns 41 when Control Center shows 42%. The code is result(Int(level * 100)). What causes this, and what is the fix?
Show answer
batteryLevel is a Float, and level * 100 can come out slightly below the whole number (for example 41.999996). Int(...) truncates toward zero, so it gives 41. Round before converting: result(Int((level * 100).rounded())).
Exercise
A Dart call to invokeMethod('getBatteryLevel') never completes, and no error appears. The Swift handle method has a guard statement that returns early on a failed argument check. What is the likely bug?
Show answer
The early-return path never calls result, so the Dart Future stays pending. Every path through handle must call result exactly once. In the guard failure branch, call result(FlutterError(...)) before returning.