0
1

More than 1 year has passed since last update.

(Flutter)Google Maps PlatformのiOS用APIキーの隠蔽と利用

Posted at

google_maps_flutterをiOSで使う場合、Google Maps Platformから発行されたAPIキーをAppDelegate.swiftに書き込む必要があります。
https://pub.dev/packages/google_maps_flutter#ios

ただ、

  • APIキーをswiftコードにハードコーディングするのは嫌
  • Android側と設定ファイルをひとつにまとめておきたい

の両方を実現する方法がなかなか見つからず苦戦しました。
(実際にはSwiftやiOSアプリ開発への知識が皆無だったため遠回りした感はありますが)
また、日本語記事の情報がほとんど見つからなかったので、非常に簡記ながら投稿しておくことにしました。

Android側の設定については、既にdart-define-from-fileを使っていました。
dart-define-from-fileの使い方は、このサイトが平易に書かれておりわかりやすかったです。

上サイトでもiOSについての記述もありますが、肝心のAppDelegate.swiftへの反映の仕方がよくわかりませんでした。
で、見つけたのがこちらこちら

要は、

  1. dart-define-from-fileでAPIキーを書いたJSONファイルを読み込む
  2. JSONファイルで指定したキーでinfo.plistへ設定値を取得
  3. info.plistで指定したキーでAppDelegate.swiftへ設定値を取得

という感じでAppDelegate.swiftへAPIキーを注入できるようです。

サンプルコード

dart-define/env.json
{
    "apiKey":"APIキーを書いておく"
}
info.plist
<dict>
    ・・・
	<key>API_KEY</key> 
	<string>$(apiKey)</string>
    ・・・
</dict>
AppDelegate.swift
import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let apiKey = Bundle.main.infoDictionary!["API_KEY"] as! String
    GMSServices.provideAPIKey(apiKey) // google_maps_flutterで利用する場合
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1