我想将用户的位置方法与LocationUtils分开,以便我可以使用它们并且不必继续编写重复的方法,但我正在努力做到这一点,是否有我可以学习的资源?我是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 :(得分: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广播您的其他视图控制器可以监听的事件。