Todos los productos
Search
Centro de documentos

Mobile Platform as a Service:Integración con iOS

Última actualización: Sep 05, 2026

Agregue el plugin de Location a un proyecto iOS existente mediante CocoaPods para acceder a las API de servicios basados en ubicación (LBS) y obtener datos de ubicación del dispositivo.

Requisitos previos

Antes de empezar, asegúrese de contar con lo siguiente:

Agregar el SDK

Utilice el plugin cocoapods-mPaaS para agregar el SDK del componente Location a su proyecto.

  1. En su Podfile, agregue la dependencia del componente Location: mPaaS_pod "mPaaS_LBS".image.png

  2. Ejecute pod install desde la línea de comandos. Una vez completada la instalación, abra el archivo .xcworkspace generado en Xcode; no abra directamente el archivo .xcodeproj.

  3. Habilite las alertas de ubicación en su proyecto de Xcode. Vaya a la pestaña Signing & Capabilities de su target o agregue directamente las cadenas de descripción de uso obligatorias al archivo Info.plist:

    • Para ubicación en primer plano: agregue NSLocationWhenInUseUsageDescription con un mensaje que explique por qué su aplicación necesita acceso a la ubicación.

    • Para ubicación en segundo plano: agregue también NSLocationAlwaysAndWhenInUseUsageDescription.

    Si su proyecto ya incluye estas claves de Info.plist debido a un framework de ubicación existente (como Amap), omita este paso.image.png

Uso del SDK

Los siguientes ejemplos se basan en la demostración de Location oficial y aplican a la versión base 10.1.32 y posteriores. El módulo APMobileLBS devuelve la latitud y longitud actuales del dispositivo.

Nota

El SDK de Location no admite geocodificación inversa. Para obtener resultados de geocodificación inversa, llame directamente a la API de Amap.

Referencia de API

Configurar parámetros con MPLBSConfiguration

/**
 Configuration for the location service.
 */
@interface MPLBSConfiguration : NSObject

/** The desired accuracy for a single location request, in meters. Pass an acceptable positive number based on your scenario, such as 500 for a 500 m range. */
@property (nonatomic, assign) CLLocationAccuracy desiredAccuracy;

/** The acceptable cache duration for a single location request. This value specifies how long a cached location is valid, measured back from the current time. Set the cache time to 30s or longer. */
@property (nonatomic, assign) APCoreLocationCacheAvaliable cacheTimeInterval;

/** The timeout period for a single location request or reverse geocoding query, in seconds. The default and minimum value is 2s. */
@property (nonatomic, assign) NSTimeInterval timeOut;

/** The information level for the reverse geocoding query. The default is APCoreLocationReGeoLevelDistrict. */
@property (nonatomic, assign) LBSLocationReGeoLevel reGeoLevel;

/** The location information for the reverse geocoding query. Specify the latitude and longitude coordinates in this parameter. */
@property (nonatomic, strong) CLLocation *reGeoLocation;

/** Specifies whether the location information for the reverse geocoding query uses the Amap coordinate system. The default is YES. This parameter takes effect only when the reGeoLocation parameter is used. */
@property (nonatomic, assign) BOOL reGeoCoordinateConverted;

/** Specifies whether to enable the check-in feature. The default is NO. Enable it as needed. */
@property (nonatomic, assign) BOOL needCheckIn;

/**
 *  Specifies whether high-accuracy location is required. iOS versions earlier than 14 do not differentiate accuracy. For iOS 14 and later, the default is NO (low accuracy). Specify whether your service requires high-accuracy location.
 */
@property (nonatomic,assign) BOOL highAccuracyRequired;

@end

Iniciar una solicitud de ubicación con MPLBSLocationManager

/**
 The callback block for the location result.

 @param success Specifies whether the operation was successful.
 @param locationInfo The location information.
 @param error The error message if the location request failed.
 */
typedef void(^MPLBSLocationCompletionBlock)(BOOL success,
                                            MPLBSLocationInfo *locationInfo,
                                            NSError *error);

/**
 The location service.
 */
@interface MPLBSLocationManager : NSObject

/**
 Initializes the instance.

 @param configuration The parameter settings.
 @return An instance.
 */
- (instancetype)initWithConfiguration:(MPLBSConfiguration *)configuration;

/**
 Initiates a single location request.

 @param needReGeocode Specifies whether reverse geocoding information is needed. Because the location service does not support reverse geocoding, pass NO for this parameter.
 @param block The callback block for when the location request is complete.
 */
- (void)requestLocationNeedReGeocode:(BOOL)needReGeocode
                   completionHandler:(MPLBSLocationCompletionBlock)block;

Descripción de MPLBSLocationInfo en la devolución de llamada

/**
 Reverse geocoding information.
 */
@interface MPLBSReGeocodeInfo : NSObject

@property (nonatomic, strong) NSString* country;        // Country
@property (nonatomic, strong) NSString* countryCode;    // Country code
@property (nonatomic, strong) NSString* provience;      // Province
@property (nonatomic, strong) NSString* city;           // City
@property (nonatomic, strong) NSString* district;       // District
@property (nonatomic, strong) NSString* street;         // Street
@property (nonatomic, strong) NSString* streetCode;     // Street code
@property (nonatomic, strong) NSString* cityCode;       // City code
@property (nonatomic, strong) NSString* adCode;         // Administrative region code
@property (nonatomic, strong) NSArray* poiList;         // POI list

@end

/**
 The data structure for location information in the location result.
 */
@interface MPLBSLocationInfo : NSObject

@property (nonatomic, strong) CLLocation* location;         // Location information
@property (nonatomic, strong) MPLBSReGeocodeInfo* rgcInfo;  // Reverse geocoding information

@end

Ejemplo de código

El siguiente ejemplo obtiene la ubicación del dispositivo y muestra el resultado, incluidas las coordenadas, la precisión y si la ubicación precisa está habilitada.

- (void)getLocation {
    MPLBSConfiguration *configuration = [[MPLBSConfiguration alloc] init];
    configuration.desiredAccuracy = kCLLocationAccuracyBest;

    self.locationManager = [[MPLBSLocationManager alloc] initWithConfiguration:configuration];
    [self.locationManager requestLocationNeedReGeocode:NO completionHandler:^(BOOL success, MPLBSLocationInfo * _Nonnull locationInfo, NSError * _Nonnull error) {
        NSString *message;
        if (success) {
            message = [NSString stringWithFormat:@"Location successful. Longitude: %.5f, Latitude: %.5f, Accuracy: %.3f, High accuracy: %d", locationInfo.location.coordinate.longitude, locationInfo.location.coordinate.latitude, locationInfo.location.horizontalAccuracy, !locationInfo.location.ap_lbs_is_high_accuracy_close];
        } else {
            message = [NSString stringWithFormat:@"%@", error];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            AUNoticeDialog *alert = [[AUNoticeDialog alloc] initWithTitle:@"Location Result" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });
    }];
}

Adaptación para iOS 14

iOS 14 introdujo la ubicación precisa como un permiso por aplicación. Los usuarios pueden activarla o desactivarla al otorgar acceso a la ubicación y modificarla posteriormente en Configuración. El SDK gestiona ambos escenarios mediante el parámetro highAccuracyRequired y el campo ap_lbs_is_high_accuracy_close.

Adaptación de parámetros de entrada

Establezca highAccuracyRequired en MPLBSConfiguration para declarar si su función requiere ubicación precisa. Si establece highAccuracyRequired = YES pero el usuario no ha otorgado el permiso de alta precisión, la devolución de llamada devolverá un error en lugar de un resultado de ubicación.

/**
 Configuration for the location service.
 */
@interface MPLBSConfiguration : NSObject

/**
 *  Specifies whether high-accuracy location is required. iOS versions earlier than 14 do not differentiate accuracy. For iOS 14 and later, the default is NO (low accuracy). Specify whether your service requires high-accuracy location.
 */
@property (nonatomic,assign) BOOL highAccuracyRequired;

@end
// If highAccuracyRequired is set to YES and high-accuracy location permission is not granted, an error is returned in the callback.
Errorcode: APCoreLocationErrorCodeHighAccuracyAuthorization

Adaptación de la devolución de llamada

Cuando highAccuracyRequired = NO (o se omite el parámetro), la devolución de llamada se ejecuta correctamente sin importar la configuración de precisión del usuario. El objeto CLLocation devuelto incluye el campo ap_lbs_is_high_accuracy_close, que su aplicación puede leer para determinar si la ubicación precisa estaba disponible.

// Response parameter modification
@interface CLLocation (APMobileLBS)
/*
 *  Specifies whether precise location is disabled. The default is NO.
 */
@property(nonatomic,assign)BOOL ap_lbs_is_high_accuracy_close;
@end

Ejemplo de código

- (void)getLocationWithHighAccuracy {
    MPLBSConfiguration *configuration = [[MPLBSConfiguration alloc] init];
    configuration.desiredAccuracy = kCLLocationAccuracyBest;
    configuration.highAccuracyRequired = YES;

    self.locationManager = [[MPLBSLocationManager alloc] initWithConfiguration:configuration];
    [self.locationManager requestLocationNeedReGeocode:NO completionHandler:^(BOOL success, MPLBSLocationInfo * _Nonnull locationInfo, NSError * _Nonnull error) {
        NSString *message;
        if (success) {
            message = [NSString stringWithFormat:@"Location successful. Longitude: %.5f, Latitude: %.5f, Accuracy: %.3f, High accuracy: %d", locationInfo.location.coordinate.longitude, locationInfo.location.coordinate.latitude, locationInfo.location.horizontalAccuracy, !locationInfo.location.ap_lbs_is_high_accuracy_close];
        } else {
            message = [NSString stringWithFormat:@"%@", error];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            AUNoticeDialog *alert = [[AUNoticeDialog alloc] initWithTitle:@"Location Result" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        });
    }];
}