App进入前景时获取新位置

时间:2013-08-01 02:51:33

标签: iphone ios objective-c cllocationmanager

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

但是,如果应用程序被发送到后台,则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;
}

0 个答案:

没有答案