ios - handling location permissions instantaneously in swift -
i trying implement basic map view , add user's current location map annotation. have added requestwheninuse key info.plist , imported corelocation.
in view controller's did load method, have following:
locmanager.requestwheninuseauthorization() var currentlocation : cllocation if(cllocationmanager.authorizationstatus() == clauthorizationstatus.authorizedwheninuse){ currentlocation = locmanager.location println("currentlocation \(currentlocation)") } else{ println("not getting location") // default pin } i getting prompt re. permission retrieve location. happening getting print saying not getting location, because runs before user gets chance tap ok. if elave app , come in can retrieve location , add map. however, want when user taps ok first time able grab current location , add map there , then. how can achieve this? have following method adding pin:
func addpin(location2d: cllocationcoordinate2d){ self.mapview.delegate = self var newpoint = mkpointannotation() newpoint.coordinate = location2d self.mapview.addannotation(newpoint) }
in order that, need implement methoddidchangeauthorizationstatus location manager delegate called shortly after cllocationmanager initialized.
to that, in class using location, add delegate protocol. in viewdidload method (or applicationdidfinishlaunching if in appdelegate) initialize location manager , set delegate property self:
class mycoolclass: cllocationmanagerdelegate { var locmanager: cllocationmanager! override func viewdidload() { locmanager = cllocationmanager() locmanager.delegate = self } } finally, implement locationmanager(_ didchangeauthorizationstatus _) method in body of class declared previously, method called when status of authorization changed, user clicked button. can implement this:
func locationmanager(manager: cllocationmanager!, didchangeauthorizationstatus status: clauthorizationstatus) { switch status { case .notdetermined: // if status has not yet been determied, ask authorization manager.requestwheninuseauthorization() break case .authorizedwheninuse: // if authorized when in use manager.startupdatinglocation() break case .authorizedalways: // if authorized manager.startupdatinglocation() break case .restricted: // if restricted e.g. parental controls. user can't enable location services break case .denied: // if user denied app access location services, can grant access settings.app break default: break } } that way can handle each , every case, wether user gave permission or revoked it.
Comments
Post a Comment