ios - 错误 EXC 错误指令试图从另一个类获取当前位置?

标签 ios swift google-maps architecture currentlocation

我有一个 Massive View Controller 并试图将我的代码分成不同的类。 我创建了一个类 CurrentLocation。在 View Controller 中,我调用了 google maps 方法 animateToLocation,我得到了一条 EXC Bad Instruction。已经对适当的应用程序架构进行了大量研究,但仍然是新的,需要通过经验学习。使用适用于 iOS 的谷歌地图并尝试正确实现。将更新位置与 ViewController 放在单独的类中是否可以接受然后只需调用我希望在 ViewController 中调用的方法?我在想我已经正确地实现了模型- View - Controller ,也许只是继承了一些我不应该拥有的东西。应该是一个简单的修复,只是不知道从哪里开始。

import UIKit
import GoogleMaps

class ViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {

@IBOutlet weak var googleMapView: GMSMapView!

let locationManager = CLLocationManager()
let currentLocation = CurrentLocation()

override func viewDidLoad() {
    super.viewDidLoad()
    currentLocation.trackLocation 
}

override func viewDidAppear(animated: Bool)
 {
    super.viewDidAppear(animated)

    if CLLocationManager.locationServicesEnabled() {
        googleMapView.myLocationEnabled = true

        googleMapView.animateToLocation(currentLocation.coordinate) // EXC Bad Instruction
    } else
    {
        locationManager.requestWhenInUseAuthorization()
    }

}



import Foundation
import CoreLocation
import GoogleMaps

class CurrentLocation: NSObject,CLLocationManagerDelegate {

override init()
{
    super.init()
}

var locationManager = CLLocationManager()

var location   : CLLocation!
var coordinate : CLLocationCoordinate2D!
var latitude   : CLLocationDegrees!
var longitude  : CLLocationDegrees!

 func trackLocation()
{
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{

    if CLLocationManager.locationServicesEnabled() {
        location   = locations.last
        coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        latitude   = coordinate.latitude
        longitude  = coordinate.longitude
    }

}

最佳答案

发生此错误是因为 currentLocation.coordinatenil 并且您正在将其作为隐式展开的可选对象进行访问。基本上,您试图在变量包含任何内容之前访问它。您需要初始化一个 CLLocationManager,请求权限,然后开始更新位置。查看来自 NSHipster 的这篇精彩文章:Core Location in i​OS 8 .

关于ios - 错误 EXC 错误指令试图从另一个类获取当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35382963/

相关文章:

swift - 在 firebase 上使用 facebook 登录的正确方法是什么? swift

mysql - 在 Google map 上追踪位置路径

google-maps - 无法在 Flutter 上全屏加载 map_view

ios - 如何根据我的 json 响应数组制作标签栏(ios swift)

ios - NSLayoutConstraint 不适用于 uibutton 和 uilabel

swift - 如何在swift中将回调函数传递给另一个函数?

ios - 如何在 Swift 中定义 MIDINotifyProc?

javascript - 单击状态栏不会滚动到应用程序顶部 (Trigger.io)

android - PhoneGap 开发者应用下载错误

swift - 谷歌地图 View 颜色错误