2016-11-17 80 views
0

我想將用戶的位置方法分開到LocationUtils,以便我可以使用它們,並且不必一直在寫重複的方法,但我正在努力做到這一點,是否有我可以學習的資源?我是iOS新手。如何靜態獲取用戶位置並將其用於其他課程iOS?

class LocationUtils: NSObject, CLLocationManagerDelegate { 
    let locationManager = CLLocationManager() 
    var userCity: String? 

    func enableLocationServices() { 
    self.locationManager.requestAlwaysAuthorization() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.delegate = self // Comment 
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     locationManager.startUpdatingLocation() 
    } 
    self.locationManager.requestLocation() 
    } 


    // Try ro call this statically 
    func getUsersClosestCity(lat: CLLocationDegrees, lng: CLLocationDegrees){ 
    let geoCoder = CLGeocoder() 
    let location = CLLocation(latitude: lat, longitude: lng) 
    geoCoder.reverseGeocodeLocation(location) { 
     (placemarks, error) -> Void in 

     let placeArray = placemarks as [CLPlacemark]! 
     var placeMark: CLPlacemark! 
     // Can the array throw an exception 
     placeMark = placeArray?[0] 
     if (placeMark != nil) { 
     //userCity = placeMark.addressDictionary?["City"] as? String? 
     self.userCity = placeMark.addressDictionary?["City"] as? String 

     } 

    } 

    } 
    func getUserCity() -> String? { 
    return self.userCity 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate 
    self.getUsersClosestCity(lat: locValue.latitude, lng: locValue.longitude) 
    } 

} 

現在我想在這個項目

這就是我用它

override func loadView() { 
    super.loadView() 
    setLocationView() 

    } 





func setLocationView() { 
    let locationLabel : UILabel = UILabel(frame: CGRect(x: UIScreen.main.bounds.width/3, y: UIScreen.main.bounds.height, width: 500, height: 21)) 
    let locationLabelFrame = CGRect(x : UIScreen.main.bounds.width/4, y: 3 * (UIScreen.main.bounds.width/4), width : 125, height : 45) 
    locationLabel.frame = locationLabelFrame 
    locationLabel.backgroundColor = UIColor.blue 
    let locUtil = LocationUtils() 
    locUtil.enableLocationServices() 
    if (locUtil.getUserCity() != nil) { 
     locationLabel.text = locUtil.getUserCity() 
    } 

    self.view.addSubview(locationLabel) 
    } 

這不添加的UILabel到視圖中使用的各種類這些方法,當我刪除的位置相關的電話,我得到一個標籤上的視圖

我將不勝感激,如果任何人可以指導我的資源,我可以學習或任何提示關於這個如何去做

謝謝

回答

0

你可以說,他能夠使用的所有viewControllers的單位置服務:

class LocationReportingService { 
    static let shared = LocationReportingService() 
    fileprivate let locationManager = CLLocationManager() 
    private override init() { 
     super.init() 
    } 
    func beginMonitoring() { 
     //insert logic here 
    } 
} 

要使用它,你叫LocationReportingService.shared.beginMonitoring()。您可以添加las知道位置的屬性,還可以通過NotificationCenter.default.post廣播其他視圖控制器可以偵聽的事件。

相關問題