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

时间:2016-02-13 17:27:07

标签: ios swift google-maps architecture currentlocation

我有一个Massive View Controller并试图将我的代码分成不同的类。 我创建了一个类CurrentLocation。在视图控制器中,我调用了谷歌地图方法animateToLocation,我得到了一个EXC错误指令。已经对适当的应用程序架构进行了大量研究,但仍然是新的,并通过经验学习。使用谷歌地图为iOS并尝试正确实现这一点。将更新位置放在ViewController的单独类中是否可以接受然后只调用我希望在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
    }

}

1 个答案:

答案 0 :(得分:1)

发生此错误是因为currentLocation.coordinatenil并且您将其作为隐式解包的可选项进行访问。基本上,您尝试在变量有任何内容之前访问变量。您需要初始化CLLocationManager,请求权限,然后开始更新位置。看看NSHipster的这篇伟大的文章:Core Location in i​OS 8