我是Xcode和Swift的新手,我正在尝试简单地创建一个显示用户当前位置并更新它的地图。到目前为止我有这个:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
var mapp = MKMapView.self
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (CLLocationManager.locationServicesEnabled())
{
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.map.showsUserLocation = true
}
else
{
print("Location services are not enabled")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView() {
//let camera = GMSCameraPosition.camera(withLatitude: 36.2108, longitude: -81.6774, zoom: 15.0)
//let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
//mapView.isMyLocationEnabled = true
//view = mapView
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
self.map.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Errors: " + error.localizedDescription)
}
}
我在故事板中制作了MapView,CTRL将其拖动到文件中(因此@IBOutlet弱变量映射:MKMapView!)。但是,当我插入手机并模拟应用程序时,它会在打开一个可选值时显示出一个"意外发现的nil"在一些打印语句之后,我发现每当我引用map变量时都会发生这种情况。为什么是这样?谢谢!
答案 0 :(得分:2)
在原帖的评论中,罗布回答了这个问题:
“
删除loadView方法。只有在以编程方式创建视图时才使用它。使用故事板(或NIB)时,将配置代码放在viewDidLoad中,而不是loadView。 - 罗布“
谢谢Rob