1

我很难实现我认为应该是一个非常简单的功能。我有一个按钮,可以将用户的位置与另一组纬度/经度坐标进行比较,并显示一个警报,告诉用户他们是“附近”还是“远离”该位置。如果应用程序保持在前台,这很有效。

但是,如果应用程序被发送到后台,locationManager 将停止更新用户的位置。如果发生这种情况,当用户重新启动应用并按下“比较位置按钮”时,应用似乎无法正确获取用户的新坐标。

将接收位置更新添加到后台模式似乎可行,但我知道这会耗尽电池电量并且可能会被 Apple 拒绝。

我真正想要的是能够让按钮等待一组准确的纬度/经度坐标,然后再尝试计算用户与其他经度/纬度坐标之间的距离。这是我到目前为止所拥有的:

位置按钮执行以下操作:

-(void) locationButton { 
    NSString *userLatitude =[(PDCAppDelegate *)[UIApplication sharedApplication].delegate 
    getUserLatitude];

    NSString *userLongitude =[(PDCAppDelegate *)[UIApplication sharedApplication].delegate 
    getUserLongitude];

    NSString *placeLatitude = [[NSUserDefaults standardUserDefaults]
                               stringForKey:@"savedLatitude"];
    NSString *placeLongitude = [[NSUserDefaults standardUserDefaults]
                                stringForKey:@"savedLongitude"];
    NSString *distanceURL = [NSString stringWithFormat:@"http://www.website.com/page.php?
    lat1=%@&lon1=%@&lat2=%@&lon2=%@",userLatitude, userLongitude, placeLatitude, 
    placeLongitude];

    NSData *distanceURLResult = [NSData dataWithContentsOfURL:[NSURL 
    URLWithString:distanceURL]];  
    NSString *distanceInFeet = [[NSString alloc] initWithData:distanceURLResult 
    encoding:NSUTF8StringEncoding];

    if ([distanceInFeet isEqualToString:@"1"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You're Near!" 
        message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;   
    }
    if ([distanceInFeet isEqualToString:@"0"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You're Far!" message:@"" 
        delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }   
}

locationButton 方法的前几行从我的 App Delegate 获取 userLatitude 和 userLongitude:

- (NSString *)getUserCoordinates {
    NSString *userCoordinates = [NSString stringWithFormat:@"latitude: %f longitude: %f", 
    locationManager.location.coordinate.latitude, 
    locationManager.location.coordinate.longitude];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
    return userCoordinates;
}

- (NSString *)getUserLatitude {
    NSString *userLatitude = [NSString stringWithFormat:@"%f", 
    locationManager.location.coordinate.latitude];
    return userLatitude;
}

- (NSString *)getUserLongitude {
    NSString *userLongitude = [NSString stringWithFormat:@"%f", 
    locationManager.location.coordinate.longitude];
    return userLongitude;
}
4

0 回答 0