swift 初始化GMSMapView崩溃

oalqel3c  于 2023-01-08  发布在  Swift
关注(0)|答案(3)|浏览(164)


My程序在初始化GMSMapView对象时崩溃。例如:

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
let store = Store.default
let map: GMSMapView = GMSMapView()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    guard GMSServices.provideAPIKey(AppConstants.Keys.googleMaps.rawValue) else { fatalError("Can not initialize Google Map services") }

    print("Map: \(self.map)")

    return true
}

初始化GMSMapView时,代码报告以下内容:

Thread 1: signal SIGABRT
libc++abi.dylib: terminating with uncaught exception of type NSException
kx1ctssn

kx1ctssn1#

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
let store = Store.default
var map: GMSMapView?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    guard GMSServices.provideAPIKey(AppConstants.Keys.googleMaps.rawValue) else { fatalError("Can not initialize Google Map services") }
    self.map = GMSMapView()
    print("Map: \(self.map)")

    return true
}

试着像这样改变它

whhtz7ly

whhtz7ly2#

检查控制台输出。您应该看到以下错误:第一个月
您尝试在GMSService.provideAPIKey之前初始化mapView

wkftcu5l

wkftcu5l3#

遵循以下步骤:

    • 步骤1:**按如下所示将API密钥添加到AppDelegate.swift

1.添加以下import语句:

import GoogleMaps

1.使用API密钥将以下代码添加到application(_:didFinishLaunchingWithOptions:)方法中:

GMSServices.provideAPIKey("YOUR_API_KEY")
    • 步骤2:**添加Map:

1.在应用的默认ViewController中添加方法,以创建和初始化GMSMapView的示例。

import UIKit
import GoogleMaps

class ViewController: UIViewController {
    var mapView: GMSMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera)
        self.view.addSubview(mapView)
  }
}

1.运行应用程序。

替代解决方案:

更改appDelegate.swift中的现有代码:

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
let store = Store.default
let map: GMSMapView!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    GMSServices.provideAPIKey(AppConstants.Keys.googleMaps.rawValue)
    let frame = CGRect(x: 0, y: 0, width: width, height: height)
    map = GMSMapView.map(withFrame: self.view.frame)
    // map object is ready to use
    print(map)
    return true
}

未知widthheight是设备屏幕尺寸。

相关问题