2017-11-05 10 views
-1

현재 위치를 반환하려는 다음 Location 클래스가 있습니다. 그러나 현재 위치를 가져올 수 없습니다. 나는 모든 올바른 PLIST 항목을 추가하고 Core Location 프레임 워크를 추가했다고 생각합니다. getLocation을 탭하면 권한이 사라지고 권한을 승인 할 수 없습니다.스위프트가 '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

빨리 찾아 주셔서 감사합니다. 죄송합니다. –