2011-08-20 93 views
3

我需要獲取當前的用戶位置,但我不知道它是否已更改。我可以從CLLocationManager請求強制位置更新嗎?或者還有其他方法可以做到嗎?如何強制更新用戶位置?

回答

13

停止並重新啓動LocationManager應強制設備重新獲取初始位置。

[locationManager stopUpdatingLocation]; 
[locationmanager startUpdatingLocation]; 
3

我在我的一個應用程序中遇到了同樣的問題。我實際上不得不改變應用程序結構。 這就是我所做的: 這個班有一個公開的方法。 - (無效)locateMe;一個抽象類需要實例化這個類並運行locateMe,然後當userIsLocated通知將被廣播時。另一種方法可以從(CLLocation *)currentLocation獲得結果座標;

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 

@interface ManageUserLocation : NSOperation <CLLocationManagerDelegate> { 
    CLLocationManager  *locationManager; 
    CLLocation    *currentLocation; 
} 
@property (nonatomic, retain) CLLocationManager  *locationManager; 
@property (nonatomic, retain) CLLocation   *currentLocation; 

-(void) locateMe; 
@end 
在.M

#import "ManageUserLocation.h" 

    @implementation ManageUserLocation 

    @synthesize locationManager; 
    @synthesize currentLocation; // Other classes use this to get the coordination even better you can make another method that even dont get the direct access to currentLocation. It is up to you. 

    - (id)init 
    { 
     self = [super init]; 
     if (self) { 
     //[self locateMe]; // Just a hook if you need to run it 
     } 
     return self; 
    } 

    -(void) locateMe { 
     self.locationManager = nil; 
     self.locationManager = [[CLLocationManager alloc] init]; 
     self.locationManager.desiredAccuracy=kCLLocationAccuracyBest; 
     self.locationManager.delegate = self; 
     [self.locationManager startUpdatingLocation]; 
    } 

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
     // User location has been found/updated, load map data now. 
     [self.locationManager stopUpdatingLocation]; 
     currentLocation = [newLocation copy]; 
     // WooHoo Tell everyone that you found the userLocation 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"userLocationIsFound" object:nil]; 
    } 

    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ 
     // Failed to find the user's location. This error occurs when the user declines the location request or has location servives turned off. 
     NSString * errorString = @"Unable to determine your current location."; 
     UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error Locating" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [errorAlert show]; 
     [errorAlert release]; 
     [locationManager stopUpdatingLocation]; 
    } 
    - (void)dealloc { #warning dont forget this :) } 
@end 

希望這有助於

0

我認爲是違反蘋果指南強制更新。蘋果公司表示,地理更新將自動發生,但在未知的時間。