Getting user's current location iOS 8.0

后端 未结 1 1672
遇见更好的自我
遇见更好的自我 2021-01-27 15:38

I trying to get users current location using MapKit and CoreLocation. I\'m really new to Objective-C. As for my research the implementation is slightly different from older iOS

1条回答
  •  孤独总比滥情好
    2021-01-27 15:51

    Your flow for requesting and starting location update is not proper. First of all the requestAlwaysAuthorization will not change the authorization status immediately because it needs user to press Allow or Don't Allow button in the alert. So you should start location update only after getting its result. Then in didUpdateLocations no need to request/start again.

    Do it in following way,

    Dn your viewDidLoad

     BOOL isAuthorized = [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways;
     if (isAuthorized) {
         [locationManager startUpdatingLocation];
     }
     else {
         [locationManager requestAlwaysAuthorization];
     }
    

    And implement the delegate methods like

    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
       CLLocation *current = locations.firstObject;
    }
    
    - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
        if(status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse){
            self.serviceLocation.showsUserLocation = YES;
           [locationManager startUpdatingLocation];
        }
    }
    

    In iOS 8 for requesting permission you should add the usage description string in the info.plist. In your case the key is NSLocationAlwaysUsageDescription.

    0 讨论(0)
提交回复
热议问题