2013-04-24 8 views
0

내 위치 애플리케이션에서 didUpdateToLocation 메소드를 구현했습니다. 이 메서드는 매 초마다 호출하고 위치 데이터를 제공합니다. 하지만 매초마다 위치를 가져올 필요가 없습니다. 매 5 분마다이 메소드를 실행해야합니다. 이것을 할 수 있습니까?매 5 분마다 GPS 위치 가져 오기

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    //initialize location lisetener on Application startup 
    self.myLocationManager = [[CLLocationManager alloc]init]; 
    self.myLocationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    self.myLocationManager.delegate = self; 
    [self.myLocationManager startUpdatingLocation]; 


    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    // Override point for customization after application launch. 
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { 
     self.viewController = [[INNOViewController alloc] initWithNibName:@"INNOViewController_iPhone" bundle:nil]; 
    } else { 
     self.viewController = [[INNOViewController alloc] initWithNibName:@"INNOViewController_iPad" bundle:nil]; 
    } 
    self.window.rootViewController = self.viewController; 
    [self.window makeKeyAndVisible]; 
    return YES; 
} 


-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    /* 
    if(self.executingInBackground) 
    { 
     NSLog(@"Aplication running in background"); 
    } 
    else 
    { 
     NSLog(@"Aplication NOT running in background"); 
    } 
    */ 


    //NSLog(@"new location->%@ and old location -> %@",newLocation,oldLocation); 

    NSString *urlAsString = @"http://www.apple.com"; 

    NSURL *url=[NSURL URLWithString:urlAsString]; 

    NSURLRequest *urlRequest=[NSURLRequest requestWithURL:url]; 

    NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 


    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

     if ([data length] > 0 && error == nil) { 
      NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSLog(@"Downloaded html -> %@",html); 
      //NSLog(@"Downloaded successfully"); 
     } 
     else if([data length] == 0 && error == nil) 
     { 
      NSLog(@"Nothing downloaded"); 
     } 
     else 
     { 
      NSLog(@"Error occured -> %@",error); 
     } 

    }]; 
} 
+1

5 분마다 얻고 싶다면 아마 타이머를 사용해야합니다. 5 분 카운트 다운으로 타이머를 시작하고 가장 정확한 위치를 얻은 다음 다시 시작하고 반복하십시오. –

+0

위치 관리자 개체를 초기화하고 타이머 내부에서 청취를 시작하면 응용 프로그램이 백그라운드로 이동하면 didUpdateToLocation 이벤트가 실행됩니까? – Ramprasad

+1

백그라운드의 응용 프로그램이 활성화되어 있지 않으므로이 응용 프로그램은 실행되지 않습니다. 또는 운영 체제가 백그라운드 모드로 작동하도록 요청할 수 있지만 응용 프로그램이 VOIP 또는 탐색 응용 프로그램과 같은 특정 종류가 아닌 경우 제한된 시간 동안이 옵션이 부여됩니다. 그것들은 배경에 특권을 가지고있다. –

답변

2

accuraccy과의 거리 필터를 줄이고, 이것은 당신이 당신이 강제로 방법의 stopupdating를 호출 할 수 있습니다이 5 분 후에 호출 할 경우 방법이
라고하는 빈도를 줄일 수 있으며, 매 5를 startupdating합니다 분

3

kCLLocationAccuracyBest을 요청했기 때문에 신속하게 호출됩니다. 물러서 라. 그것은 시간을 기준으로하지 않으며 델타 거리를 기준으로합니다. 그 정확도로 거리의 작은 변화라도 수신율이 좋은 지역에서 업데이트가 시작됩니다. 다른 값을 사용하십시오.

다시 말하지만,이 방법은 시간에 기반하여 사용되지 않습니다. 그들은 델타 거리을 기반으로 사용하기위한 것입니다. 대신

1

:

[self.myLocationManager startUpdatingLocation]; 

사용 : 그것은 각 초에 위임 메소드를 호출합니다 startUpdatingLocation : 당신이 사용하는 경우

[self.myLocationManager startMonitoringSignificantLocationChanges]; 

. startMonitoringSignificantLocationChanges을 사용하면 중요한 위치 변경이 발생하거나 5 분 간격 후에 대리자 메서드가 호출됩니다.


startMonitoringSignificantLocationChanges

Starts the generation of updates based on significant location changes. - (void)startMonitoringSignificantLocationChanges

Discussion

This method initiates the delivery of location events asynchronously, returning shortly after you call it. Location events are delivered to your delegate’s locationManager:didUpdateLocations: method. The first event to be delivered is usually the most recently cached location event (if any) but may be a newer event in some circumstances. Obtaining a current location fix may take several additional seconds, so be sure to check the timestamps on the location events in your delegate method.

After returning a current location fix, the receiver generates update events only when a significant change in the user’s location is detected. For example, it might generate a new event when the device becomes associated with a different cell tower. It does not rely on the value in the distanceFilter property to generate events. Calling this method several times in succession does not automatically result in new events being generated. Calling stopMonitoringSignificantLocationChanges in between, however, does cause a new initial event to be sent the next time you call this method.

If you start this service and your application is subsequently terminated, the system automatically relaunches the application into the background if a new event arrives. In such a case, the options dictionary passed to the locationManager:didUpdateLocations: method of your application delegate contains the key UIApplicationLaunchOptionsLocationKey to indicate that your application was launched because of a location event. Upon relaunch, you must still configure a location manager object and call this method to continue receiving location events. When you restart location services, the current event is delivered to your delegate immediately. In addition, the location property of your location manager object is populated with the most recent location object even before you start location services.

In addition to your delegate object implementing the locationManager:didUpdateLocations: method, it should also implement the locationManager:didFailWithError: method to respond to potential errors.

Note: Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently than once every five minutes. If the device is able to retrieve data from the network, the location manager is much more likely to deliver notifications in a timely manner.

Declared In CLLocationManager.h

참조 CLLocationManager

+0

"5 분마다 한 번 이상 알림을받지 못합니다"는 "5 분마다 호출됩니다"와 동일하지 않습니다 – borrrden

+0

동일한 위치에 있어도 5 분마다 이벤트를 실행해야합니다. – Ramprasad

+1

@Ram 그럼 나는 5 분마다 타이머를 호출하는 자신의 메서드를 작성하십시오. 위치가 바뀔 때마다 그냥 어딘가에 저장하고 다음에 메소드를 호출 할 때 사용하십시오. 그러나 백그라운드에서 이것을 할 수있을 것으로 기대하지 마십시오. – borrrden

1

당신은 startMonitoringSignificantLocationChanges 대신 startUpdatingLocation 사용할 수 있습니다. 마지막 위치에서 약 500 미터 이동했을 때만 업데이트됩니다.

관련 문제