2016-03-27 9 views
8

私はXCode v7.2.1、Simulator v9.2を使用しています。私のシンプルマッププロジェクトは、シミュレータで自分の位置を取得&表示しません。

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() 
     } 
    } 

} 

私はNSLocationWhenInUseUsageDescription下図のようにInfo.plistの中を追加しました:

私はマップ&が&を地図上に表示し、私の場所を取得することになっていることを示すのUIViewControllerを持っています

enter image description here

また、デバッグ - >場所 - >カスタムロケーション...を選択し、経度を設定しましたヘルシンキ、フィンランドの緯度、以下のように:私は私のアプリを実行すると、それは私の場所を得ることはありませんが enter image description here

、地図が、示されています。どうして? (地図のどこにでも青い点が表示されないという意味です)。

===== UPDATE ====

私のアプリは、しかし、それはどちらか助けていませんが、動作しているとき、私はまたを試してみました。

+0

あなたが設定する必要がありますを追加する必要が 'showsUserLocation = true'をとにかく、私が最初にユーザーの許可を求める必要はありませ条件 – Azat

+0

によって、その後の位置を示しています。とにかく、私の条件付きコードにも間違いはありません。 –

+0

次のような状況を考えてみましょう:ユーザーがコントローラを開き、場所を使用することに同意した後、 'requestWhenInUseAuthorization()'を実行しても何も起こらない場合、マップ上に位置を示すコードがなくなり、コントローラ – Azat

答えて

7

あなたはユーザーの所在地をリクエストしていますが、実際には何もしないでください。ロケーションマネージャの代理人になり、承認変更に対応します。

このコードは7.2.1で私の作品(デバッグで「アップル」を選択した後に - >所在地):私は@Caseyの答えに同意するが、時にはあなたが少しを行う必要があり

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

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 
関連する問題