2017-01-09 6 views
0

Swift에서 앱이 열려있는 동안 사용자의 현재 위치를 찾는 함수의 값을 사용하여 변수/상수를 설정하려고합니다. 인쇄 기능의 주석을 제거하면 좌표가 성공적으로 인쇄되지만 함수 외부의 값에는 액세스 할 수 없습니다.별도의 변수/상수로 CLLocationManager에서 좌표를 가져올 수 없습니다.

나는 현재 MainVC 클래스의 일부로서 MainVC.swift 파일에 내 코드의 일부로서이 있습니다

"Cannot use instance member 'locationManager' within property initializer; property initializers run before 'self' is available".

:이 오류에 직면하고 있습니다 그러나

import UIKit 
import MapKit 
import CoreLocation 

class MainVC: UIViewController, CLLocationManagerDelegate { 
    //Map 
    @IBOutlet weak var map: MKMapView! 

    let manager = CLLocationManager() 
    let coordinates = locationManager() 
    //I've also tried using let coordinates = currentCoords 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     manager.delegate = self 
     manager.desiredAccuracy = kCLLocationAccuracyBest 
     manager.requestWhenInUseAuthorization() 
     manager.startUpdatingLocation() 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) -> String { 
     let location = locations[0] 

     let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01) 
     let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) 
     let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span) 
     map.setRegion(region, animated: true) 
     lat = String(myLocation.latitude) 
     long = String(myLocation.longitude) 
     let currentCoords:String = "\(lat);\(long)" 

     //print(currentCoords) 
     self.map.showsUserLocation = true 

     return currentCoords 
    } 
} 

내가 코드를 변경하고

let coordinates = currentCoords 

를 사용하는 경우

나는 다른 오류 보여주는를 얻을 :

"Use of unresolved identifier 'currentCoords'"

저는 게으른 var 및 lazy let을 사용해 보았습니다.

+0

게시 한 코드의 컨텍스트를 조금 더 제공해야합니다. – rmaddy

+0

이니셜 라이저에 오류가 있습니까? ** 이니셜 라이저 **에서 오류를 가져 오는 코드를 붙여 넣으십시오. – Honey

+0

@rmaddy 그 점에 대해 사과드립니다. 원래 게시 할 때 추가하는 것을 잊어 버렸습니다. 메인 포스트를 도움이되는 정보로 업데이트했습니다. – Miles

답변

0

당신은 단지 locationManager.location에 액세스 할 수 있어야합니다 .coordinate 내 buttonClick의 방법으로 :

import UIKit 
import MapKit 

class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate { 

    let locationManager = CLLocationManager() 

    @IBAction func buttonClick(_ sender: Any) { 
     let location = locationManager.location?.coordinate 
     let lat:Double = (location?.latitude)! 
     let lon:Double = (location?.longitude)! 
     print(lat,lon) 
    } 

    @IBOutlet weak var mapView: MKMapView! 

     override func viewDidLoad() { 
     super.viewDidLoad() 

     mapView.delegate = self 
     mapView.showsUserLocation = true 
     mapView.userTrackingMode = .follow 

     locationManager.delegate = self 
     locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 

    } 

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

    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 
     print("viewDidAppear") 
     // status is not determined 
     if CLLocationManager.authorizationStatus() == .notDetermined { 
      locationManager.requestAlwaysAuthorization() 
     } 
      // authorization were denied 
     else if CLLocationManager.authorizationStatus() == .denied { 
      showAlert("Location services were previously denied. Please enable location services for this app in Settings.") 
     } 
      // we do have authorization 
     else if CLLocationManager.authorizationStatus() == .authorizedAlways { 
      locationManager.startUpdatingLocation() 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     print("didUpdateLocations") 
     print(locations.last?.coordinate) 
    } 

    func showAlert(_ title: String) { 
     let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in 
      alert.dismiss(animated: true, completion: nil) 
     })) 
     self.present(alert, animated: true, completion: nil) 

    } 
} 
+0

안녕하세요, 게시 해 주셔서 감사합니다. 나는 이런 식으로하려고했지만 어떤 이유로 그것은 ether를 좋아하지 않는다. 나는 내일 맥북에 도착하자마자 그 방법으로 얻는 에러를 게시 할 것이다. – Miles

+0

다음 오류가 발생합니다 : '(MainVC) -> (CLLocationManager, [CLLocation]) -> String'의 멤버 '위치가 없습니다' ' – Miles

+0

이 오류의 원인이되는 코드를 게시하십시오. – CoderMike

0

이것은 당신이

let coordinates:CLLocation = nil 

그런 다음 didUpdateLocations 할당에 공개 변수를 정의하는 방법이다 locations 배열의 마지막 요소를 가진 좌표 변수. 그러면 어디서나 액세스 할 수 있습니다. didUpdateLocations는 최대 몇 초 후에 호출 될 수 있으므로 공개 변수 좌표가 채워지는 데 몇 초 정도 걸릴 수 있습니다.

func coordinatesBecomeAvailable() { 
    // Here you can print your coordinates or start using them for the first time 
} 
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
let firstTime:Bool = (coordinates == nil) 
coordinates = locations[0] 
if (firstTime) // This is first time this function is called 
    coordinatesBecomeAvailable() 
...... 
< Rest of your code here > 
...... 
< This function does have any return value! no String nothing > 
} 

좌표 값이 nil인지 여부 만 확인하면됩니다. 또는 didUpdateLocations 내부에서이 위임 메서드가 처음으로 호출되는지 여부를 확인할 수 있습니다. 이것은 위치 관리 프로그램을 초기화하고 사용하는 가장 효율적이고 완벽한 방법은 아니며 문제와 관련된 코드를 방금 게시했다고 가정합니다.

+0

코드를 변경하고 추가했지만 좌표를 인쇄 할 때 아무 것도 표시하지 않습니다. – Miles

+0

좌표를 사용할 수있게되었을 때 좌표를 인쇄 할 수 있도록 코드를 변경했습니다. –

+0

@robycyr 어떤 이유로 든 여전히 무의미 해졌습니다 – Miles