Sub topic 5
Handling method calls on iOS with Swift
This chapter covers the iOS half of a MethodChannel: registering a handler in Swift, reading arguments, and replying with a value, an error, or "not implemented". It assumes you have read the earlier chapters on channel architecture, codecs, and the Dart side of MethodChannel. It also assumes you can read basic Swift and know the ios/ folder of a Flutter project (Runner/AppDelegate.swift).
The role of the iOS handler
On the Dart side, invokeMethod sends a message containing a method name and optional arguments. On iOS, you register a closure that receives each message and must reply to it. The channel name must match the Dart name exactly, including case. A mismatch is not a compile error. The call fails at runtime with a MissingPluginException in Dart.
Registering the channel
The handler is attached to a FlutterMethodChannel. Creating one needs a name and a binary messenger. The messenger is the object that carries the raw bytes between Dart and the host.
import UIKit
import Flutter
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(
name: "com.example.app/battery",
binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
switch call.method {
case "getBatteryLevel":
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == .unknown {
result(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil))
} else {
result(Int(device.batteryLevel * 100))
}
default:
result(FlutterMethodNotImplemented)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}The pieces, in order:
window?.rootViewController as! FlutterViewControllerfetches the view controller that hosts Flutter. ItsbinaryMessengerproperty is what the channel needs.setMethodCallHandlertakes a closure with two parameters.callis aFlutterMethodCall, andresultis aFlutterResult, which is a closure of type(Any?) -> Void.resultis marked@escapingbecause you may call it after the handler returns, for example after an asynchronous operation finishes.GeneratedPluginRegistrant.register(with: self)registers the plugins your app depends on. Keep it in the method, as the template does.
The device.isBatteryMonitoringEnabled = true line matters. Without it, batteryLevel returns -1.0 and batteryState stays .unknown. On the iOS Simulator the state is also .unknown, so this handler returns the UNAVAILABLE error there. Test it on a real device.
The `FlutterMethodCall` object
A FlutterMethodCall has two properties:
| Property | Swift type | Meaning |
|---|---|---|
| `method` | `String` | The method name passed to `invokeMethod` |
| `arguments` | `Any?` | The decoded arguments, or `nil` if Dart passed none |
arguments is untyped. The standard codec decodes whatever Dart sent, so you cast it yourself. The usual convention is to send a Dart Map and read it as [String: Any].
Here is the Dart caller:
import 'package:flutter/services.dart';
class GreetingService {
static const MethodChannel _channel =
MethodChannel('com.example.app/greeting');
Future<String?> greet(String name) {
return _channel.invokeMethod<String>('greet', {'name': name});
}
}And the matching Swift case, which you add to the switch in the handler:
case "greet":
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String else {
result(FlutterError(code: "BAD_ARGS",
message: "Expected a String under the key 'name'.",
details: nil))
return
}
result("Hello, \(name)")Never force-unwrap arguments. Dart code can change independently of the Swift code, and a force unwrap turns a bad call into a native crash instead of a catchable Dart error. A guard with a FlutterError keeps the failure on the Dart side.
Type mapping from Dart to Swift
The standard method codec converts values at the boundary. The table below covers what you meet most often on iOS.
| Dart | Swift receives |
|---|---|
| `null` | `nil` |
| `bool` | `NSNumber(value: Bool)`, castable to `Bool` |
| `int` | `NSNumber(value: Int)`, castable to `Int` |
| `double` | `NSNumber(value: Double)`, castable to `Double` |
| `String` | `String` |
| `Uint8List` | `FlutterStandardTypedData` |
| `List` | `[Any]` |
| `Map` | `[AnyHashable: Any]`, usually cast to `[String: Any]` |
Values flow the other way with the same mapping. In the battery example, result(Int(...)) arrives in Dart as an int. Returning a type the codec does not support, such as a custom Swift struct, fails the call. Convert it to a dictionary first.
The three possible replies
Every call needs exactly one reply, and result supports three forms:
- A value.
result(42),result("text"),result(nil)orresult(["a": 1]). The DartFuturecompletes with that value. Useresult(nil)for a method that returns nothing, because skipping the call leaves theFuturepending forever. - A
FlutterError.FlutterError(code:message:details:)becomes aPlatformExceptionin Dart, with the same three fields. Pick stable, uppercase codes such asUNAVAILABLEso Dart can branch one.code. Thedetailsfield accepts any codec-supported value, so you can pass structured data. FlutterMethodNotImplemented. This is a constant you pass toresult. Dart then throws aMissingPluginException. It is the correct answer for a method name your handler does not know, which is why thedefaultbranch uses it.
Asynchronous work and threading
The method call handler runs on the iOS main thread. Anything slow, such as disk reads, network calls, or heavy computation, blocks the UI if you do it inline. Move it to a background queue and reply when it finishes:
case "readLargeFile":
guard let args = call.arguments as? [String: Any],
let path = args["path"] as? String else {
result(FlutterError(code: "BAD_ARGS", message: "Missing 'path'.", details: nil))
return
}
DispatchQueue.global(qos: .userInitiated).async {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
DispatchQueue.main.async {
result(FlutterStandardTypedData(bytes: data))
}
} catch {
DispatchQueue.main.async {
result(FlutterError(code: "IO_ERROR",
message: error.localizedDescription,
details: nil))
}
}
}The reply goes through DispatchQueue.main.async. As a rule, send replies on the main thread, as in the example above. Some Flutter versions also support task queues for running handlers off the main thread, but that is an advanced option and not required here. Any iOS API that must run on the main thread, such as UIDevice or UI calls, also belongs in a main-thread handler.
Keeping the handler maintainable
A single closure with a growing switch becomes hard to read. A common refactor moves the logic into a method and keeps the closure thin:
private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getBatteryLevel":
handleBatteryLevel(result: result)
default:
result(FlutterMethodNotImplemented)
}
}
private func handleBatteryLevel(result: FlutterResult) {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == .unknown {
result(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil))
} else {
result(Int(device.batteryLevel * 100))
}
}Register it with channel.setMethodCallHandler { [weak self] call, result in self?.handle(call, result: result) }. If self is gone, result is never called, so reply in that case instead of dropping the call:
channel.setMethodCallHandler { [weak self] call, result in
guard let self = self else {
result(FlutterError(code: "GONE", message: "Handler released.", details: nil))
return
}
self.handle(call, result: result)
}Common errors
MissingPluginExceptionon iOS only. The channel name differs from Dart's, the handler is registered after the first call, or thedefaultbranch repliedFlutterMethodNotImplementedfor a method name you misspelled. After adding native code, do a full rebuild rather than a hot reload, because hot reload does not rerunAppDelegate.- Battery level always
UNAVAILABLE. You are on the Simulator, orisBatteryMonitoringEnabledis not set. - Crash on a cast. You used
as!oncall.arguments. Useas?withguard. - Dart
Futurenever completes. A code path did not callresult. - Wrong number type. A Dart
doublesuch as3.0arrives as anNSNumber. Cast toDouble, notInt, so you do not lose the fractional part.
Exercise
Your Swift handler receives getUser with arguments {'id': 7}. You must read the id as an Int, return the string "user-7", and return an error with code BAD_ARGS if the id is missing. Which three things must the handler get right so the Dart Future always completes?
Show answer
First, read the arguments safely with guard let args = call.arguments as? [String: Any], let id = args["id"] as? Int else { ... }, never with as! or a force unwrap. Second, in the failure branch call result(FlutterError(code: "BAD_ARGS", message: "Missing 'id'.", details: nil)) and return. Third, in the success path call result("user-\(id)") exactly once. Every path then replies once, so the Dart Future completes with the string or throws a PlatformException. Any other method name falls through to default and gets result(FlutterMethodNotImplemented).
Exercise
You test a battery feature on the iOS Simulator and Dart receives a PlatformException with code UNAVAILABLE. Is the channel broken?
Show answer
No. The channel works, because the Swift handler ran and replied with a FlutterError. The Simulator reports batteryState as .unknown, so the handler takes its error branch by design. Test on a physical device, and make sure isBatteryMonitoringEnabled is set to true before reading batteryLevel.