2016-03-27 24 views
8

我正在使用XCode v7.2.1,模擬器v9.2。我的簡單地圖項目沒有得到&顯示我在模擬器中的位置

我有一個UIViewController,顯示地圖&應該接受我的位置&顯示地理位置:

import UIKit 
import MapKit 

class LocationVC: UIViewController, MKMapViewDelegate { 
    @IBOutlet weak var map: MKMapView! 

    let locationManager = CLLocationManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     map.delegate = self 
    } 

    override func viewDidAppear(animated: Bool) { 
     if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { 
      map.showsUserLocation = true 
     } else { 
      locationManager.requestWhenInUseAuthorization() 
     } 
    } 

} 

我已經加入了NSLocationWhenInUseUsageDescriptioninfo.plist中,如下圖所示:

enter image description here

我還選擇了Debug - > Location - > Custom Location ...並設置經度爲&緯度赫爾辛基,芬蘭,如下圖所示: enter image description here

當我運行我的應用程序,該地圖顯示,但是它沒有得到我的位置。爲什麼? (我的意思是我沒有在地圖的任何地方看到藍點)。

===== UPDATE ====

我也試過我的應用程序運行時,但它也沒有幫助。

+0

您應該設置'showsUserLocation = TRUE;無論如何,沒有條件 – Azat

+0

我想先問用戶的許可,則顯示的位置。無論如何,我的條件代碼也沒有錯。 –

+0

考慮以下情況:用戶打開控制器,同意使用位置,執行'requestWhenInUseAuthorization()',但此後沒有任何反應,沒有更多的代碼顯示地圖上的位置,因此用戶下次打開時只會看到藍色點控制器 – Azat

回答

7

您正在請求用戶的位置,但實際上沒有做任何響應。成爲地點經理的代表並響應授權變更。

此代碼對我的作品在7.2.1(在調試中選擇「蘋果」後 - >位置):

import UIKit 
import MapKit 

class ViewController: UIViewController, CLLocationManagerDelegate { 
    @IBOutlet weak var map: MKMapView! 

    let locationManager = CLLocationManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locationManager.delegate = self 
    } 

    override func viewDidAppear(animated: Bool) { 
     super.viewDidAppear(animated) 

     if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { 
      map.showsUserLocation = true 
     } else { 
      locationManager.requestWhenInUseAuthorization() 
     } 
    } 

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     guard status == .AuthorizedWhenInUse else { print("not enabled"); return } 
     map.showsUserLocation = true 
    } 
} 
0

我同意@Casey的回答,但有時你需要做一點點更多用CLLocationManagerDelegate方法。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    if let location = locations.first { 
     //reset mapView's center in case your custom location was wrong. 
     map.centerCoordinate = location.coordinate 
     //mannual call show annotations to avoid some bugs 
     map.showAnnotations(map.annotations, animated: true) 
    } 
} 
0

你只需要添加

locationManager.delegate = self 
mapView.showsUserLocation = true 
相關問題