我有一个 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.coordinate
是 nil
并且您正在将其作为隐式展开的可选对象进行访问。基本上,您试图在变量包含任何内容之前访问它。您需要初始化一个 CLLocationManager
,请求权限,然后开始更新位置。查看来自 NSHipster 的这篇精彩文章:Core Location in iOS 8 .
关于ios - 错误 EXC 错误指令试图从另一个类获取当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35382963/