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

error EXC Bad Instruction trying to get current location from another class?

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

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.