1

我正在开发一个基于位置的移动应用程序。即使应用程序被终止/终止,我的应用程序也会使用用户的当前位置更新服务器。在集成谷歌地点选择器 API 之前,我的应用程序运行良好。为 ios 安装 google place picker API 后,我的应用程序仅在 5 到 10 分钟内更新位置,然后停止更新位置。

//我的代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


// Initialize Location Manager
sLocationManager;


//the system automatically relaunches the application into the background if a new event arrives.
// The options dictionary passed to the application:didFinishLaunchingWithOptions: method of your application  delegate contains the key UIApplicationLaunchOptionsLocationKey to indicate that your application was launched because of a location event

if (launchOptions[UIApplicationLaunchOptionsLocationKey]) {

    NSLog(@"---UIApplicationLaunchOptionsLocationKey");


    sLocationManager.locationUpdatedInBackground = ^(NSArray<CLLocation *> *locations) {

        NSLog(@"---setLocationUpdatedInBackground");

        [sLocationModule saveNewLocations];

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:300];
        notification.alertBody = @"Your location was changed. Please run application for tracking your geoposition with best accuracy.";
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];

        [sLocationManager startMonitoringSignificantLocationChanges];
    };

}else {

    sLocationManager.locationUpdatedInForeground = ^(NSArray<CLLocation *> *locations) {

        NSLog(@"---setLocationUpdatedInForeground");

        [sLocationModule saveNewLocations];
    };

    sLocationManager.locationUpdatedInBackground = ^(NSArray<CLLocation *> *locations) {

        NSLog(@"---setLocationUpdatedInBackground");

        [sLocationModule saveNewLocations];

        [sLocationManager startDeferredLocationUpdates];
    };


    // Notifications

    [application cancelAllLocalNotifications];
}
return YES;

//位置管理器

 #pragma mark - CLLocationManager Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)aLocations {

    NSString *infoMessage = [NSString stringWithFormat:@"%@", aLocations];
    NSLog(@"%@", infoMessage);

    locations = [@[] mutableCopy];

    NSLog(@"locations=%@",locations);

    [aLocations enumerateObjectsUsingBlock:^(CLLocation * _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {


        // Check for location errors (speed -1.00 mps / course -1.00)
       // if (location.speed >= 0 &&
        //    location.course >= 0) {

            if (locations.count > 0) {
                if ([location.timestamp timeIntervalSinceDate:[locations lastObject].timestamp] > dLocationManagerDistanceFilter ||
                    [location distanceFromLocation:[locations lastObject]] > dLocationUpdatesUntilTimeout) {


                    [locations addObject:location];
                    NSLog(@"location.timestamp>dLocationManagerDistanceFilter**** locations=%@",locations);
                }
            } else
                [locations addObject:location];
                NSLog(@"else***locations=%@",locations);

        //save location in userdefaults

        NSString *latitudeValue = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
        NSString *longitudeValue = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
        NSLog(@"new location is recieved Lat : %@  Long : %@",latitudeValue,longitudeValue);

        [User setUserLat:latitudeValue];
        [User setUserLon:longitudeValue];

       // }
    }];

    if ([self isInBackground]) {

        NSLog(@"app is in background***");

        if (self.locationUpdatedInBackground) {

            backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: ^{

                [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
            }];


            self.locationUpdatedInBackground(locations);

            [delegate locationManagerDidUpdateLocationInBackground];

            [[NSNotificationCenter defaultCenter] postNotificationName:nLocationManagerDidUpdateLocationInBackgroundNotification
                                                                object:nil
                                                              userInfo:nil];

            [self endBackgroundTask];
        }
    } else {

        if (self.locationUpdatedInForeground) {

            if([[NSUserDefaults standardUserDefaults]objectForKey:@"userIdKey"]){

            self.locationUpdatedInForeground(locations);


            [delegate locationManagerDidUpdateLocationInForeground];

            [[NSNotificationCenter defaultCenter] postNotificationName:nLocationManagerDidUpdateLocationInForegroundNotification
                                                                object:nil
                                                              userInfo:nil];


            }

        }
    }
}

添加地点选择器的代码

#pragma mark - Place picker delegate methods

  - (IBAction)pickPlace:(id)sender {
                //dismiss the keyboard
                [tfLocation resignFirstResponder];


                CLLocationCoordinate2D center = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude);
                CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(center.latitude + 0.001, center.longitude + 0.001);
                CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(center.latitude - 0.001, center.longitude - 0.001);
                GMSCoordinateBounds *viewport = [[GMSCoordinateBounds alloc] initWithCoordinate:northEast
                                                                                     coordinate:southWest];
                GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:viewport];
                _placePicker = [[GMSPlacePicker alloc] initWithConfig:config];

                [_placePicker pickPlaceWithCallback:^(GMSPlace *place, NSError *error) {
                    if (error != nil) {
                        NSLog(@"Pick Place error %@", [error localizedDescription]);
                        return;
                    }

                    if (place != nil) {
                        NSLog(@"Place name %@", place.name);
                        NSLog(@"Place address %@", place.formattedAddress);
                        NSLog(@"Place attributions %@", place.attributions.string);

                        // NSString *latitudeValue = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude];
                        // NSString *longitudeValue = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.longitude];

                        tfLocation.text=place.formattedAddress;
                        locationPoint=[NSString stringWithFormat:@"%f,%f", place.coordinate.latitude,place.coordinate.longitude];

                    } else {
                        NSLog(@"No place selected");
                    }
                }];
            }


        // Add a UIButton in Interface Builder, and connect the action to this function.
        - (IBAction)getCurrentPlace:(UIButton *)sender {
            [_placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *placeLikelihoodList, NSError *error){
                if (error != nil) {
                    NSLog(@"Pick Place error %@", [error localizedDescription]);
                    return;
                }

                self.nameLabel.text = @"No current place";
                self.addressLabel.text = @"";

                if (placeLikelihoodList != nil) {
                    GMSPlace *place = [[[placeLikelihoodList likelihoods] firstObject] place];
                    if (place != nil) {
                        self.nameLabel.text = place.name;
                        self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:@", "]
                                                  componentsJoinedByString:@"\n"];
                    }
                }
            }];
        }

    // Present the autocomplete view controller when the button is pressed.
    - (IBAction)onLaunchClicked:(id)sender {
        GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
        acController.delegate = self;
        [self presentViewController:acController animated:YES completion:nil];
    }

    // Handle the user's selection.
    - (void)viewController:(GMSAutocompleteViewController *)viewController
    didAutocompleteWithPlace:(GMSPlace *)place {
        [self dismissViewControllerAnimated:YES completion:nil];
        // Do something with the selected place.
        NSLog(@"Place name %@", place.name);
        NSLog(@"Place address %@", place.formattedAddress);
        NSLog(@"Place attributions %@", place.attributions.string);
    }

    - (void)viewController:(GMSAutocompleteViewController *)viewController
    didFailAutocompleteWithError:(NSError *)error {
        [self dismissViewControllerAnimated:YES completion:nil];
        // TODO: handle the error.
        NSLog(@"Error: %@", [error description]);
    }

    // User canceled the operation.
    - (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
        [self dismissViewControllerAnimated:YES completion:nil];
    }

    // Turn the network activity indicator on and off again.
    - (void)didRequestAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    }

    - (void)didUpdateAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }

谁能告诉我,我在这里做错了什么?在不影响后台位置更新的情况下最好使用地点选择器,还是有任何其他方式来选择地点/位置,就像 ios 中的谷歌地点选择器?请帮助我或告诉我其他解决方案。

谢谢你!

4

0 回答 0