iOS 8에서 작동하지 않는 위치 서비스


608

iOS 7에서 제대로 작동하는 내 앱은 iOS 8 SDK에서 작동하지 않습니다.

CLLocationManager위치를 반환하지 않으며 설정 -> 위치 서비스 에도 내 앱이 표시되지 않습니다 . 문제에 대한 Google 검색을 수행했지만 아무 것도 나타나지 않았습니다. 무엇이 잘못 될 수 있습니까?



19
iOS 8의 위치 관리자에 대한 변경 사항 중 일부를 여기에 게시했습니다. nevan.net/2014/09/core-location-manager-changes-in-ios-8
— nevan king

2
이 라이브러리를 사용하여 핵심 위치 API를 단순화하고 멋진 블록 기반 인터페이스를 제공하고 다른 iOS 버전 간의 모든 차이점을 정규화
— lms

여기에 약간의 참조가 있습니다 datacalculation.blogspot.in/2014/11/…
— iOS 테스트

2
@nevanking 당신은 선생님! 왕관이 필요해! 나는 변화 이후이 문제와 싸워 왔고 아직 그것을 고치는 방법에 대한 "가이드"를 찾지 못했습니다. 그것은 멍청한 일이었습니다. 당신의 가이드는 저처럼 바보를 만들었습니다. 그 링크에 감사드립니다.
— Patrick R

답변:


1086

나는 내 자신의 문제를 해결하게되었습니다.

위치 업데이트를 시작하기 전에 iOS 8 SDK에서 requestAlwaysAuthorization(배경 위치의 경우) 또는 requestWhenInUseAuthorization(전경의 경우에만 위치) 호출 CLLocationManager이 필요합니다.

프롬프트에 표시 할 메시지 가 NSLocationAlwaysUsageDescription있거나 NSLocationWhenInUseUsageDescription키 Info.plist를 입력해야합니다. 이것들을 추가하면 내 문제가 해결되었습니다.

여기에 이미지 설명을 입력하십시오

그것이 다른 누군가를 돕기를 바랍니다.

편집 : 자세한 내용은 다음을 참조하십시오 : Core-Location-Manager-Changes-in-ios-8


6
Info.plist에서 업데이트 된 정확한 값을 공유 할 수 있습니까? 내 Info.plist에서 해당 키를 볼 수 없습니다. 나는 그것을 추가했지만 여전히 작동하지 않는 것 같습니다. Swift, iOS8 및 XCode 6 베타 4를 사용하고 있습니다.
— Vijay Kumar AB

4
@Vjay-편집기에서 Info.plist 파일을 편집해야합니다 (베타 6 현재). Xcode에서 해당 키를 설정할 수 없습니다.
— Kendall Helmstetter Gelner

11
사용자에게 사용자 정의 설명을 표시하지 않으려면이 키를 빈 문자열로 설정하십시오.
— nonamelive

7
작동하려면 locationManager를 유지해야합니다. 따라서 CLLocationManager를 강력한 속성으로 만드십시오
— Vassily

273
plist 항목을 제외하면 오류, 경고, 로그 메시지가 표시되지 않습니다. 기본적으로 Apple은 적절한 plist 항목이 없으면 아무것도하지 않는 API 호출을 만들었습니다. 이것을 알아 낸 @OrtwinGentz에게 감사합니다.
— MobileVet

314

나는 같은 문제로 머리카락을 뽑고있었습니다. Xcode는 당신에게 오류를 제공합니다 :

MapKit위치 승인을 요구하지 않고 위치 업데이트 를 시작하려고합니다 . 호출해야합니다 -[CLLocationManager requestWhenInUseAuthorization]또는 -[CLLocationManager requestAlwaysAuthorization]첫째.

그러나 위의 방법 중 하나를 구현하더라도 info.plist에 NSLocationAlwaysUsageDescription또는 에 대한 항목이 없으면 사용자에게 프롬프트하지 않습니다 NSLocationWhenInUseUsageDescription.

info.plist에 다음 행을 추가하십시오. 여기서 문자열 값은 사용자 위치에 액세스해야하는 이유를 나타냅니다.

<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>

Xcode 5 에서이 프로젝트를 시작한 이후 이러한 항목이 누락되었을 수 있습니다. Xcode 6 이이 키에 대한 기본 항목을 추가 할 수는 있지만 추측하지 못했습니다.

이 두 설정에 대한 자세한 내용은 여기를 참조하십시오.


13
xcode 6은 기본적으로 이러한 키를 추가하지 않습니다. CLLocationManager를 구현하려는 경우 수동으로 추가해야합니다.
— Wesley Smith

1
나는 또한 이것을 수동으로 추가해야했지만 Xcode6에서 info.plist의 RawValues보기를 통해 추가 할 수 없었습니다!
— Kendall Helmstetter Gelner

1
나는 이것을 영원히 찾았다. 내 [CLLLocationManager authorizationStatus] 메시지는 <nil> 값만 반환했습니다. 위의 키를 추가 한 후 메시지 출력에 대한 각 열거를 반환하기 시작했습니다. ive에서 찾은 것은 알려진 iOS 8 버그이지만 내 컨텍스트에서 오랫동안 찾을 수 없었습니다. 감사합니다!
— MrOli3000

4
나는 당신이 넣은 문자열 값을 좋아합니다
— Chris Chen

1
메시지는 사용자가 자신의 위치를 ​​공유 할 것인지 묻는 경고의 하위 메시지로 나타납니다. 따라서 단순히 비어있는 (공백)은 내 응용 프로그램에서 가장 의미가있는 것 같습니다. 위치를 사용하려는 이유에 대한 설명도 의미가 있습니다. 그러나 NSLocationWhenInUseUsageDescription이 나에게 예상대로 작동하지 않았습니다 (즉, 반환 값이 정확하더라도 권한 거부가 계속 유지됨). NSLocationAlwaysUsageDescription이 제대로 작동했습니다.
— arcady bob

104

이것이 iOS 7과 호환되는지 확인하려면 사용자가 iOS 8 또는 iOS 7을 실행 중인지 확인해야합니다. 예를 들면 다음과 같습니다.

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

//In ViewDidLoad
if(IS_OS_8_OR_LATER) {
   [self.locationManager requestAlwaysAuthorization];
}

[self.locationManager startUpdatingLocation];

164
버전을 확인하는 것보다 더 좋은 방법은 객체에 해당 선택기가 있는지 확인하는 것입니다. 예 : if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { ...
— progrmr

1
Xcode 5를 빌드 할 때 @progrmr의 솔루션을 구현하는 데 문제가있었습니다 requestAlwaysAuthorization. 메서드가 무엇인지 모르기 때문 입니다. 내 추가 솔루션은 if일반적인 메소드 호출 대신 문 에서이 줄을 사용하는 것입니다 [self.locationManager performSelector:@selector(requestAlwaysAuthorization)];. 어쩌면 이것은 다른 사람들에게 명백 할 수도 있지만 알아내는 데 시간이 걸렸습니다. 최종 Xcode 6이 출시 될 때까지 올바른 솔루션이라고 생각합니다.
— VinceFior

2
올바른 솔루션은 Xcode 6으로 빌드하는 것입니다. Xcode 5로 빌드하는 경우 인증을 요청할 필요가 없으며 자동입니다.
— progrmr

당신은 포인트가있을 수 있습니다. 내 관심사는 팀이 Xcode 6으로 전환하는 동안 Xcode 5에서 코드를 컴파일하고 싶었습니다 (Xcode 6으로 컴파일하지 않으면 iOS 8에서는 작동하지 않더라도).하지만 코드를 정상적으로 작성하는 것이 더 나은 워크 플로우 일 수 있습니다. Xcode 6으로 옮길 때까지 병합하지 마십시오. 감사합니다.
— VinceFior

@VinceFior 권장되는 방법은 조건부 SDK 정의 된 매크로를 사용하여 컴파일하는 것입니다 __IPHONE_OS_VERSION_MAX_ALLOWED( #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000)
— 스티븐 크레이머

50
- (void)startLocationManager
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; //whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
    [locationManager requestWhenInUseAuthorization]; // Add This Line


}

info.plist 파일로 여기에 이미지 설명을 입력하십시오



2
@Hemang : Apple Dev 설명서에 따르면 앱의 인증 상태를 결정하기 전에 위치 서비스를 시작하는 것이 안전합니다. 위치 서비스를 시작할 수 있지만 해당 서비스는 권한 부여 상태가 kCLAuthorizationStatusAuthorizedAlways 또는 kCLAuthorizationStatusAuthorizedWhenInUse로 변경 될 때까지 데이터를 전달하지 않습니다.
— Andrew

조금 늦었지만 plist 파일의 관련이없는 부분, 특히 FacebookAppID를 숨길 것을 권장합니다.
— Przemysław Wrzesiński

고마워 그러나 그것은 단지 더미 샘플입니다 :)
— neo D1

또한 프로젝트가 올바른 info.plist (키가 정의 된)를 가리키는 것이 중요합니다 . Info.plist 파일의 프로젝트 빌드 설정에서 결정됩니다.
— clearlight

30

애플 문서에 따르면 :

iOS 8 부터는 앱의 Info.plist 파일 에 a NSLocationWhenInUseUsageDescription또는 NSLocationAlwaysUsageDescription키 값이 있어야합니다. 그런 다음 전화로 [self.myLocationManager requestWhenInUseAuthorization]또는 [self.myLocationManager requestAlwaysAuthorization]필요에 따라 위치 업데이트를 등록하기 전에 사용자에게 권한을 요청 해야합니다. 그러면 Info.plist에 입력 한 문자열이 다음 대화 상자에 표시됩니다.

사용자가 권한을 부여하면 평상시와 동일합니다. 권한을 거부하면 대리인에게 위치 업데이트를 알리지 않습니다.



28
- (void)viewDidLoad
{

    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];

    self.locationManager.delegate = self;
    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
        NSUInteger code = [CLLocationManager authorizationStatus];
        if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
            // choose one request according to your business.
            if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
                [self.locationManager requestAlwaysAuthorization];
            } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
                [self.locationManager  requestWhenInUseAuthorization];
            } else {
                NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
            }
        }
    }
    [self.locationManager startUpdatingLocation];
}

>  #pragma mark - CLLocationManagerDelegate

    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
        NSLog(@"didFailWithError: %@", error);
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
    }

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {
        NSLog(@"didUpdateToLocation: %@", newLocation);
        CLLocation *currentLocation = newLocation;

        if (currentLocation != nil) {
            longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
            latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        }
    }

iOS 8에서는 위치 작업을 수행하기 위해 두 가지 추가 작업을 수행해야합니다. Info.plist에 키를 추가하고 위치 관리자에게 시작을 요청하는 권한 부여를 요청하십시오. 새로운 위치 인증을위한 두 개의 Info.plist 키가 있습니다. 이 키 중 하나 또는 둘 다 필요합니다. 키가 없으면 startUpdatingLocation을 호출 할 수 있지만 위치 관리자는 실제로 시작되지 않습니다. 시작하지 않았기 때문에 실패 할 수 없으므로 실패 메시지를 대리인에게 보내지 않습니다. 키 중 하나 또는 둘 다를 추가했지만 명시 적으로 권한 부여를 요청하지 않으면 실패합니다. 따라서 가장 먼저해야 할 일은 Info.plist 파일에 다음 키 중 하나 또는 둘 다를 추가하는 것입니다.

  • NSLocationWhenInUseUsageDescription 설명
  • NSLocation 항상 사용법 설명

이 두 키는 모두 문자열을 취합니다.

위치 서비스가 필요한 이유에 대한 설명입니다. iOS 7에서와 같이 InfoPlist.strings 파일에서 현지화 할 수있는 "현재 위치를 확인하려면 위치가 필요합니다"와 같은 문자열을 입력 할 수 있습니다.

여기에 이미지 설명을 입력하십시오


19

Xcode 5에서 컴파일 할 수있는 내 솔루션 :

#ifdef __IPHONE_8_0
    NSUInteger code = [CLLocationManager authorizationStatus];
    if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
        // choose one request according to your business.
        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
            [self.locationManager requestAlwaysAuthorization];
        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
            [self.locationManager  requestWhenInUseAuthorization];
        } else {
            NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
        }
    }
#endif
    [self.locationManager startUpdatingLocation];

2
모든 앱에서 사용할 수있는 멋진 동적 솔루션입니다. 순서를 변경하고 iphone 8.0을 확인하는 대신 위치 관리자가 인증에 응답하는지 확인한 다음 authorizationstatus를 실행하여 코드를 가져옵니다. 이것은 더 보편적이 될 것입니다.
— zirinisp

xCode 7.2에서도 작동했습니다.
— 토토로

17

위치를 묻는 이전 코드는 iOS 8에서 작동하지 않습니다. 위치 인증을 위해이 방법을 시도 할 수 있습니다.

- (void)requestAlwaysAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status ==        kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" :   @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestAlwaysAuthorization];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // Send the user to the Settings for this app
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}

UIAlertView는 더 이상 사용되지 않습니다. 대신 UIAlertController를 사용해야합니다.
— Pasan Premaratne

예, 더 이상 사용되지 않는다는 것을 알고 있지만 작동합니다. 그러나 예는 IOS8에 UIAlertController를 사용하는 것이 좋습니다.
— Nits007ak

12

iOS 8에서는 위치 작업을 위해 두 가지 추가 작업을 수행해야합니다. Info.plist에 키를 추가하고 위치 관리자에게 시작을 요청하는 권한 부여를 요청하십시오.

info.plist :

<key>NSLocationUsageDescription</key>
<string>I need location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>I need location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>I need location</string>

이것을 코드에 추가하십시오

if (IS_OS_8_OR_LATER)
{
    [locationmanager requestWhenInUseAuthorization];

    [locationmanager requestAlwaysAuthorization];
}

1
의사 코드가 전 처리기 호출인지 일반 호출인지 확실하지 않습니다
— El Dude

1
당신의 constants.h 또는 .PCH 파일이 추가 : #DEFINE IS_OS_8_OR_LATER ([[UIDevice currentDevice] .systemVersion하는 FloatValue]> = 8.0)
— OxenBoxen

당신이 모두를 요청할 것입니다 왜, 당신은 하나 따라 다른 응용 프로그램의 요구에 사용하는 경우에만 언급 코멘트를 추가해야합니다
— powerj1984을

info.plist 부분은 Unity3d에서 수행하기에 충분히 쉽지만 unity3d를 사용하는 경우 어떻게 코드 부분을 추가합니까? 어디 ?
— CthulhuJon

11

Swift 개발자에게 공통적 인 한 가지 오류 :

먼저 NSLocationWhenInUseUsageDescription또는 의 plist에 값을 추가하십시오 NSLocationAlwaysUsageDescription.

당신이 경우 여전히 윈도우가 인증을 요청하는 팝업 표시되지 않는, 당신은 라인을 가하고 있는지 살펴 var locationManager = CLLocationManager()보기 컨트롤러의에서 viewDidLoad방법. 그렇게하면을 호출하더라도 locationManager.requestWhenInUseAuthorization()아무 것도 표시되지 않습니다. viewDidLoad가 실행 된 후 locationManager 변수가 할당 해제 (지워짐)하기 때문입니다.

해결책은 var locationManager = CLLocationManager()클래스 메소드의 맨 위에 줄을 찾는 것입니다.


9

전에 [locationManager startUpdatingLocation];iOS8 위치 서비스 요청을 추가하십시오.

if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    [locationManager requestAlwaysAuthorization];

앱을 수정 하고 사용자에게 표시 될 문자열 값으로 Info.plist키 NSLocationAlwaysUsageDescription를 추가하십시오 (예 :We do our best to preserve your battery life. :)

앱이 열려있는 동안에 만 앱에 위치 서비스가 필요한 경우 다음을 교체하십시오.

requestAlwaysAuthorization로 requestWhenInUseAuthorization와

NSLocationAlwaysUsageDescription로 NSLocationWhenInUseUsageDescription.


9

iOS 8로 업그레이드 된 앱을 작업 중이었고 위치 서비스가 작동을 멈췄습니다. 디버그 영역에서 다음과 같이 오류가 발생합니다.

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

나는 가장 관입적인 절차를 수행했다. 먼저 NSLocationAlwaysUsageDescriptioninfo.plist 에 항목을 추가 하십시오.

여기에 이미지 설명을 입력하십시오

이 키의 값을 채우지 않았습니다. 이것은 여전히 ​​작동하며 이것이 사내 앱이기 때문에 걱정하지 않습니다. 또한 위치 서비스를 사용하라는 제목이 이미 있으므로 중복 작업을 원하지 않습니다.

다음으로 iOS 8에 대한 조건을 만들었습니다.

if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [_locationManager requestAlwaysAuthorization];
}

이 후 locationManager:didChangeAuthorizationStatus:메소드가 호출됩니다.

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:  (CLAuthorizationStatus)status
{
    [self gotoCurrenLocation];
}

이제 모든 것이 잘 작동합니다. 항상 그렇듯이 문서를 확인하십시오 .


7

이전 버전과의 호환성을 가진 솔루션 :

SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined &&
    [self.locationManager respondsToSelector:requestSelector]) {
    [self.locationManager performSelector:requestSelector withObject:NULL];
} else {
    [self.locationManager startUpdatingLocation];
}

Info.plist에서 NSLocationWhenInUseUsageDescription 키 설정


2
이것은 정확하지 않습니다. kCLAuthorizationStatusDenied의 경우는 어떻습니까? 다른 곳으로 이동하여 올바르지 않은 위치를 업데이트하기 시작합니다!
— electronix384128

@ BenMarten 나는 그것이 중요하다고 생각하지 않습니다. 당신은 자신을 처리해야합니다 locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error. 그러나 그는 if 문에 startUpdatingLocation을 추가하는 것을 잊어 버렸으므로 수락하거나 거부 한 후에 실제로 startUpdateLocation을 호출하지 않습니다.
— Chris

6

Xcode 경고를 생성하지 않는 이전 버전과의 호환성이있는 솔루션 :

SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined &&
  [self.locationManager respondsToSelector:requestSelector]) {
((void (*)(id, SEL))[self.locationManager methodForSelector:requestSelector])(self.locationManager, requestSelector);
  [self.locationManager startUpdatingLocation];
} else {
  [self.locationManager startUpdatingLocation];
}

NSLocationWhenInUseUsageDescription귀하의 설정 키Info.plist .

iOS 버전 11.0 이상 :의 설정 NSLocationAlwaysAndWhenInUseUsageDescription키 Info.plist. 다른 2 개의 키와 함께.


이것은 정확하지 않습니다. kCLAuthorizationStatusDenied의 경우는 어떻습니까? 다른 곳으로 이동하여 올바르지 않은 위치를 업데이트하기 시작합니다!
— electronix384128

Jacob의 솔루션조차도 정확 해 보이지만 나에게는 효과가 없었습니다. 이상하지만 일했다! !!
— josh

호출 [self.locationManager startUpdatingLocation] requestWhenInUseAuthorization은 아무 소용이 없습니다 직후
— 코스 티아 김

5

이것은 iOS 8의 문제입니다. 코드에 추가하십시오

if (IS_OS_8_OR_LATER)
{
    [locationmanager requestWhenInUseAuthorization];

    [locationmanager requestAlwaysAuthorization];
}

그리고 info.plist에 :

 <key>NSLocationUsageDescription</key>
 <string>I need location</string>
 <key>NSLocationAlwaysUsageDescription</key>
 <string>I need location</string>
 <key>NSLocationWhenInUseUsageDescription</key>
 <string>I need location</string>

NSLocationUsageDescription는 iOS8 +에서 사용되지 않습니다
— Carlos Ricardo

4

iOS 8에서 사용자 위치에 액세스하려면

NSLocationAlwaysUsageDescription in the Info.plist 

현재 위치를 얻을 수있는 권한을 사용자에게 요청합니다.


4

Objective-C 절차 다음 지침을 따르십시오.

iOS-11의 경우 iOS 11의 경우이 답변을 살펴보십시오.iOS 11 위치 액세스

plist에 두 개의 키를 추가하고 아래 이미지와 같은 메시지를 제공해야합니다.

 1. NSLocationAlwaysAndWhenInUseUsageDescription 
 2. NSLocationWhenInUseUsageDescription
 3. NSLocationAlwaysUsageDescription

여기에 이미지 설명을 입력하십시오 iOS-10 이하의 경우 :

NSLocationWhenInUseUsageDescription

여기에 이미지 설명을 입력하십시오

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
    [locationManager requestWhenInUseAuthorization];
}else{
    [locationManager startUpdatingLocation];
} 

위임 방법

#pragma mark - Lolcation Update 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
        {
            // do some error handling
        }
            break;
        default:{
            [locationManager startUpdatingLocation];
        }
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    userLatitude =  [NSString stringWithFormat:@"%f", location.coordinate.latitude] ;
    userLongitude =  [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    [locationManager stopUpdatingLocation];
}

신속한 절차

아래 지침을 따르십시오.

iOS-11의 경우 iOS 11의 경우이 답변을 살펴보십시오. iOS 11 위치 액세스

plist에 두 개의 키를 추가하고 아래 이미지와 같은 메시지를 제공해야합니다.

 1. NSLocationAlwaysAndWhenInUseUsageDescription 
 2. NSLocationWhenInUseUsageDescription
 3. NSLocationAlwaysUsageDescription

여기에 이미지 설명을 입력하십시오 iOS-10 이하의 경우 :

여기에 이미지 설명을 입력하십시오

import CoreLocation
class ViewController: UIViewController ,CLLocationManagerDelegate {
var locationManager = CLLocationManager()

//MARK- Update Location 
func updateMyLocation(){
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    if locationManager.respondsToSelector(#selector(CLLocationManager.requestWhenInUseAuthorization)){
       locationManager.requestWhenInUseAuthorization()
    }
    else{
        locationManager.startUpdatingLocation()
    }
}

위임 방법

//MARK: Location Update
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    NSLog("Error to update location :%@",error)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .NotDetermined: break
    case .Restricted: break
    case .Denied:
            NSLog("do some error handling")
        break
    default:
        locationManager.startUpdatingLocation()
    }
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
     let location = locations.last! as CLLocation
    var latitude = location.coordinate.latitude
    var longitude = location.coordinate.longitude

}

NSLocationAlwaysUsageDescription도 추가했는지 확인하십시오. 그렇지 않으면 앱 스토어에 업로드하는 동안 오류가 발생합니다.
— Alok

메시지는 유익한 정보 여야합니다. 그렇지 않으면 프로세스를 다시 진행하는 동안 Apple이 앱을 거부합니다.
— Alok

3

사용하는 사람들을 위해 자 마린을 , 나는 키를 추가했다 NSLocationWhenInUseUsageDescription단지 - 그것은 하나 자 마린 5.5.3 빌드 6 엑스 코드 6.1의 드롭 다운에서 사용할 수없는 수동으로부터의 Info.plist에 NSLocationUsageDescription목록에, 그리고 그이 (가) 발생 CLLocationManager에 계속 조용히 실패합니다.


2
        // ** Don't forget to add NSLocationWhenInUseUsageDescription in MyApp-Info.plist and give it a string

        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];


    // Location Manager Delegate Methods    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        NSLog(@"%@", [locations lastObject]);

}

2

하나 이상의 Info.plist 파일이있는 모든 사용자를위한 작은 도우미 ...

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Add NSLocationWhenInUseUsageDescription string' {} 

현재 디렉토리 (및 하위 폴더)의 모든 Info.plist 파일에 필요한 태그를 추가합니다.

다른 것은 :

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Set NSLocationWhenInUseUsageDescription $YOURDESCRIPTION' {} 

모든 파일에 설명을 추가합니다.



2

iOS9에서도 비슷한 오류가 발생합니다 (Xcode 7 및 Swift 2로 작업) : 위치 승인을 요구하지 않고 MapKit 위치 업데이트를 시작하려고합니다. 먼저-[CLLocationManager requestWhenInUseAuthorization] 또는-[CLLocationManager requestAlwaysAuthorization]을 호출해야합니다. 튜토리얼을 따르고 있었지만 교사는 iOS8과 Swift 1.2를 사용하고있었습니다. Xcode 7 및 Swift 2에 몇 가지 변경 사항이 있습니다.이 코드를 찾았으며 누군가에게 도움이 필요한 경우 제대로 작동합니다.

import UIKit
import MapKit
import CoreLocation

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    // MARK: Properties
    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true

    }

    // MARK: - Location Delegate Methods

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
        self.mapView.setRegion(region, animated: true)
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Errors: " + error.localizedDescription)
    }
}

마지막으로 info.plist : Information Property List : NSLocationWhenInUseUsageDescription Value : App에 직원을위한 위치 서버가 필요합니다.


2

iOS에서 사용자 위치에 액세스합니다. 두 개의 키를 추가해야합니다

NSLocationWhenInUseUsageDescription 설명

NSLocation 항상 사용법 설명

Info.plist 파일에.

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Because I want to know where you are!</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Want to know where you are!</string>

아래 이미지를 참조하십시오.

Info.plist 이미지


1
  1. 각 대상에서 각각 GPS를 사용하도록 요청하는 문자열로 키 NSLocationWhenInUseUsageDescription또는 NSLocationAlwaysUsageDescription(배경 GPS 사용)을 추가하십시오 info.plist.

  2. 다음을 실행하여 권한을 요청하십시오.

    [self initLocationManager : locationManager];

어디에 initLocationManager:

// asks for GPS authorization on iOS 8
-(void) initLocationManager:(CLLocationManager *) locationManager{

    locationManager = [[CLLocationManager alloc]init];

    if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        [locationManager requestAlwaysAuthorization];
}

info.plist각 대상 에 대해 키가 각각없는 경우 앱은 사용자에게 묻지 않습니다. 이 if기능은 iOS 7과의 호환성을 제공하며이 respondsToSelector:방법은 iOS 7 및 8의 문제를 해결하는 것보다 향후 호환성을 보장합니다.


0

나를위한 문제는 CLLocationManagerDelegate모든 클래스 가 개인 클래스이므로 모든 대리자 메서드가 호출되지 않았다는 것입니다. 그것은 매우 흔한 상황이 아니라고 생각하지만 t는 누군가를 도울 수 있다고 생각합니다.


0

iOS 8.4, iPad mini 2InfoPlist.strings 에서 해당 키를 추가 합니다. 나는 어떤 키 등을 설정하지 마십시오 내에서, .NSLocationWhenInUseUsageDescriptionInfo.plist


InfoPlist.strings :

"NSLocationWhenInUseUsageDescription" = "I need GPS information....";

이 스레드에 대한 자료는 ,이 말 as in iOS 7의 InfoPlist.strings에서 지역화 할 수 있습니다. 필자의 테스트에서는 해당 키를 파일에서 직접 구성 할 수 있습니다 InfoPlist.strings.

따라서 가장 먼저해야 할 일은 Info.plist 파일에 다음 키 중 하나 이상을 추가하는 것입니다.

  • NSLocationWhenInUseUsageDescription 설명
  • NSLocation 항상 사용법 설명

이 두 키는 모두 위치 서비스가 필요한 이유를 설명하는 문자열을 가져옵니다. iOS 7 에서와 같이 InfoPlist.strings 파일에서 현지화 할 수있는 "현재 위치를 확인하려면 위치가 필요합니다"와 같은 문자열을 입력 할 수 있습니다.


최신 정보:

@IOS의 방법이 더 좋다고 생각 합니다. Info.plist빈 값으로 키를 추가 하고에 지역화 된 문자열을 추가하십시오 InfoPlist.strings.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.