2016-10-05 114 views
0

我是Xcode和Swift的新手,我試圖製作一張地圖,顯示用戶當前的位置並更新它。我有這個至今:MKMapView似乎是零?

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弱VAR圖:的MKMapView)。但是,當我插入手機並模擬應用程序時,它給了我一個「意外發現的零,同時解開可選值」,並且在某些打印語句後,我發現每當引用地圖變量時都會發生這種情況。爲什麼是這樣?謝謝!

+0

你檢查你的應用程序的功能選項卡?地圖應該在那裏(默認關閉)。 – lithium

+3

刪除'loadView'方法。僅當您以編程方式創建視圖時才使用它。在使用故事板(或NIB)時,您將配置代碼放在'viewDidLoad'中,而不是'loadView'。 – Rob

+0

@Rob是對的。刪除'loadView',它應該工作。 –

回答

1

在原崗位的評論,羅布回答了這個問題:。


取出的loadView方法它只是用來當您以編程方式創建視圖使用故事板(或發鈔銀行),你把你的在viewDidLoad中配置代碼,不是的loadView - 羅布」

謝謝羅布