2017-11-05 8 views
-1

次のLocationクラスを持っており、現在の場所を返すことができます。しかし、私は現在の場所を取得することはできません。私はすべての正しいPLISTアイテムを追加して、Core Locationフレームワークを追加したと思います。 getLocationをタップすると、権限が消え、権限を承認できません。Swiftが `didUpdateLocations`をトリガーすることができません

デバッガは、次の値を返します。

CLLocationManager.locationServicesEnabled() true 
location Services Enabled 
locationManager.delegate <Shot_On_Goal.Location: 0x1c001f560> 


@IBAction func getLocation(_ sender: Any) { 

    let location = Location() 
    location.getCurrentLocation() 

} 



import Foundation 
import MapKit 
import CoreLocation 

class Location: NSObject { 

    var locationManager: CLLocationManager! 

    func getCurrentLocation() { 

     print("class->Location->getCurrentLocation") 

     locationManager = CLLocationManager() 

     if (CLLocationManager.locationServicesEnabled()) 
     { 
      print("location Services Enabled") 

      locationManager.delegate = self 
      locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
      locationManager.requestWhenInUseAuthorization() 
      locationManager.startUpdatingLocation() 

     } else { 

      locationManager.stopUpdatingLocation() 
     } 

    } 

} // class 

extension Location: CLLocationManagerDelegate { 

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

     print("class->Location->didFailWithError") 

     print("Error to update location \(error)") 
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 

     print("class->Location->didChangeAuthorization") 

     switch status { 
     case .notDetermined: 
      print("notDetermined") 
     case .restricted: 
      print("restricted") 
     case .denied: 
      print("denied") 
     case .authorizedAlways: 
      print("authorizedAlways") 
     case .authorizedWhenInUse: 
      print("authorizedWhenInUse") 
     } 
    } 

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

     print("class->Location->didUpdateLocations") 

     let locValue:CLLocationCoordinate2D = manager.location!.coordinate 
     print("locations = \(locValue.latitude) \(locValue.longitude)") 
    } 

} //extension 

答えて

2

問題は、このコードです:

let location = Location() // <-- oops 
location.getCurrentLocation() 

この場所インスタンスは、永続保持対象物(例えば、いくつかの永続のグローバルまたはインスタンスプロパティである必要がありますビューコントローラまたはアプリケーションデリゲート)。それはローカル変数ではありません。どんな仕事をすることもできるようになる前に、ただ消えてしまいます。

+0

ここに私の例を見てください:https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch22p773location/ch35p1032location/ViewController.swift私はあなたと非常に似ています。 ManagerHolderクラスに追加しますが、そのクラスを自分のルートビューコントローラのインスタンスプロパティとしてインスタンス化する方法を見てください。だから、私のコードは動作し、あなたのものはそうではありません。 – matt

+0

クイック検索をお寄せいただきありがとうございます。 –

関連する問題