You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Flutter iOS项目的AppDelegate.swift安全存储API密钥

iOS端从Git忽略的外部文件加载Google Maps API密钥(Flutter项目)

步骤1:创建本地密钥配置文件

  • 在ios/Runner目录下新建Keys.plist文件,写入以下内容(替换为你的实际API密钥):
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>GoogleMapsAPIKey</key>
        <string>你的Google Maps API密钥</string>
    </dict>
    </plist>
    
  • 将ios/Runner/Keys.plist添加到项目根目录的.gitignore文件中,防止密钥被提交:
    # iOS本地密钥文件
    ios/Runner/Keys.plist
    

步骤2:修改AppDelegate.swift读取密钥

更新AppDelegate.swift中的代码,替换硬编码的密钥,改为从Keys.plist读取:

import UIKit
import Flutter
import GoogleMaps
import flutter_local_notifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 从Keys.plist读取Google Maps API密钥
    if let path = Bundle.main.path(forResource: "Keys", ofType: "plist"),
       let keys = NSDictionary(contentsOfFile: path),
       let apiKey = keys["GoogleMapsAPIKey"] as? String {
        GMSServices.provideAPIKey(apiKey)
    } else {
        fatalError("无法加载Google Maps API密钥,请检查Keys.plist文件配置")
    }

    FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
        GeneratedPluginRegistrant.register(with: registry)
    }

    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

步骤3:确保配置文件被打包到App

  • 打开Xcode并选择Runner项目,切换到Build Phases标签页
  • 在Copy Bundle Resources列表中检查是否包含Keys.plist,如果没有,点击+按钮添加该文件,确保它会被打包进最终的App包内

这种实现逻辑和你Android端用keys.xml的方式一致,通过本地配置文件存储敏感密钥,同时通过.gitignore排除,避免密钥泄露到版本控制系统。

内容的提问来源于stack exchange,提问作者Ashad Nadeem Mahmudi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 13:41:03