2016-09-02 7 views
0

私はSwift 3のXcodeでマップの例を試しています。画面上にマップビューを配置し、プロジェクトをシミュレータで実行することができました。シミュレートされた場所を予想通りに変更すると、座標が移動するのがわかります。locationmanagerは座標を更新しません

現在の座標は印刷できません。私はクリックしたときに、locationmanagerによって与えられた座標がXcodeターミナルに表示されるように、画面上にボタンを置いた。私は以下のコードを含んでいます、showCoordinatesのボタンアクションは現在の座標を印刷することになっています。

import UIKit 
import MapKit 

class ViewController: UIViewController, CLLocationManagerDelegate { 

@IBOutlet weak var mapView: MKMapView! 

let locationManager = CLLocationManager() 


override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    locationManager.delegate = self 
    locationManager.requestWhenInUseAuthorization() 
    locationManager.startUpdatingLocation() 
} 

@IBOutlet weak var myLattitude: UILabel! // These are the labels that will show the coordinate on the screen when pressed. 
@IBOutlet weak var myLongitude: UILabel! 

@IBAction func showCoordinates(_ sender: AnyObject) { 

    let myCoordinate = locationManager.location?.coordinate 
    print(myCoordinate) // This does not work as expected 
} 


func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 
    guard status == .authorizedWhenInUse else { 
     print("Location not enabled") 
     return 
    } 

    print("Location allowed.") 
    mapView.showsUserLocation = true 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

}

Iシミュレータでこれを実行し、座標シミュレートを変更すると、マップ内の青い点は最初の位置を微移動しかしshowCoordinateボタンプリント。場所が変わっても、最初の場所が印刷されます。その機能を正しく機能させるにはどうすればいいですか?このように、直接あなたのdidUpdateLocationsコールバックで

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    showCoordinates(self) 
} 

また、あなたが入力でき、それ::

+0

'ocationManager(_ manager:didUpdateLocations:)'が呼び出されていますか? – Larme

+0

ありがとうございます。いいえ、私はそれを加えなかった。どこに置くことができますか? – Graeme

答えて

0

あなたViewControllerfunc locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

このように、あなたのshowCoordinates(_ sender: AnyObject)関数を呼び出し

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let myCoordinate = locationManager.location?.coordinate 
    print(myCoordinate) 
} 

しかし、形式を変更したい場合、または追加の操作を行う場合は、委任がより良いアプローチです単に座標を印刷するのではなく、1つの関数を変更するだけで済みます。委任を使用しない場合、同じことをしていても、別々に更新しなければならない2つの独立した関数があります。あなたがmapkitを使用している場合

+0

ありがとう、私は考えを得た。 – Graeme

0

、その後、

を印刷するmapview.userlocation

使用しています。それ以外の場合は、ロケーションマネージャデリゲートを実装する

関連する問題