swift2 - How to get users location statically and use it in other classes iOS? -
i want separate user's location methods locationutils can use them , not have keep writing duplicate methods struggling that, there resources can learn ? new 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 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 [clplacemark]! var placemark: clplacemark! // can array throw 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) } }
now want use these methods in various classes in project
that's how used it
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) }
this not add uilabel view, when remove location related calls, label on view
i appreciate if can guide me resources can learn or tips on how do
thank you
you can make singleton location service can used of viewcontrollers:
class locationreportingservice { static let shared = locationreportingservice() fileprivate let locationmanager = cllocationmanager() private override init() { super.init() } func beginmonitoring() { //insert logic here } }
to use call locationreportingservice.shared.beginmonitoring(). can add properties las know location , broadcast events notificationcenter.default.post other view controllers can listen for.
Comments
Post a Comment