2016-12-05 9 views
4

位置情報を使って簡単なiOSアプリを作りたいと思っています。残念ながら、デバイスとシミュレータの両方でテストしている間、シミュレータ上の "現在地"デバッグコードを入力しても、私は 'nil'を受け取ります。 Swift 3でCoreLocationを初めて使用したので、前回と同じ方法を使用しました。位置情報の問題3

import UIKit 
import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

    @IBOutlet weak var latitudeLabel: UILabel! 
    @IBOutlet weak var longitudeLabel: UILabel! 

    var locationManager:CLLocationManager? 
    var currentLocation:CLLocation? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let locationManager = CLLocationManager() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
     updateLabels() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     self.currentLocation = locations[0] 
    } 

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 
     print(error) 
    } 

    func updateLabels() { 
     latitudeLabel.text = String(describing: currentLocation?.coordinate.latitude) 
     longitudeLabel.text = String(describing: currentLocation?.coordinate.longitude) 
     print(currentLocation) 
} 

} 

もちろん、私はInfo.plistに必要なプライバシーキーをすべて書きました。

私はcurrentLocationを印刷しようとしていますが、私はnilを受け取ります。 アラートが表示されていますが、すぐに消えてしまうような問題が見つかりました。

+0

あなたは「私は 『ゼロ』を受ける」とはどういう意味ですか?問題を明確にしてください。応答のために – rmaddy

+0

ありがとうございます。編集された説明。 –

答えて

4

viewDidLoadには、CLLocationManagerをローカル変数に保存しますが、プロパティに保存することはありません。したがって、スコープから外れて割り当てが解除され、デリゲートメソッドが呼び出されることはありません。

プロパティを直接更新するか、ロケーションマネージャの設定が完了したら、self.locationManager = locationManagerを必ず実行してください。

override func viewDidLoad() { 
    super.viewDidLoad() 

    locationManager = CLLocationManager() 
    locationManager?.delegate = self 
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager?.requestAlwaysAuthorization() 
    locationManager?.startUpdatingLocation() 
    // updateLabels() 
} 

をそしてrmaddyが指摘したように、その後、didUpdateLocationsであなたのラベルを更新します:私はおそらくそれを直接更新したい

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    guard let location = locations.last, location.horizontalAccuracy >= 0 else { return } 

    currentLocation = location 
    updateLabels() 
} 
1

間違った場所から電話しています。updateLabelslocationManager(_:didUpdateLocations)メソッドの中から呼び出す必要があります。そしてそのデリゲートメソッドはバックグラウンドスレッドで呼び出すことができるので、DispatchQueue.main.asyncを使用してupdateLabelsに呼び出しをラップするようにしてください。