2016-11-17 78 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广播其他视图控制器可以侦听的事件。

相关问题