首页 > 解决方案 > Xcode 错误:“'AppDelegate' 类型的值没有成员 'receiveBatteryLevel' Flutter 官方 Flutter 平台频道示例

问题描述

我正在尝试使用 Swift 和 Xcode 为我的 Flutter 项目编写本机代码,对于初学者,我正在关注 Flutter 官方网站上的示例,该示例位于以下站点的 swift/ios 示例下文档的平台集成部分中,

https://flutter.dev/docs/development/platform-integration/platform-channels?tab=ios-channel-swift-tab

实现的客户端没问题我完全按照代码示例进行操作。但是,在“AppDelegate.swift”文件的本机端,我收到错误消息:“'AppDelegate' 类型的值没有成员'receiveBatteryLevel'”

根据Xcode的问题是在这一行“self?.receiveBatteryLevel(result:result)”

我在 AppDelegate.swift 中的代码如下:

import UIKit
import Flutter
import Firebase
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("myKeyGoesHere(don't mind)")
    FirebaseApp.configure()

    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
     let batteryChannel = FlutterMethodChannel(name:"samples.flutter.dev/battery",
       binaryMessenger: controller as! FlutterBinaryMessenger)


    batteryChannel.setMethodCallHandler({
         [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
        // Note: this method is invoked on the UI thread.
        // Handle battery messages.
        guard call.method == "getBatteryLevel" else {
           result(FlutterMethodNotImplemented)
           return
         }
     self?.receiveBatteryLevel(result: result)
      })


    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

private func receiveBatteryLevel(result: FlutterResult) {
  let device = UIDevice.current
  device.isBatteryMonitoringEnabled = true
  if device.batteryState == UIDevice.BatteryState.unknown {
    result(FlutterError(code: "UNAVAILABLE",message: "Battery info unavailable",details: nil)
    )
  } else {
    result(Int(device.batteryLevel * 100))
  }
}

标签: iosswiftflutter

解决方案


推荐阅读