2017-04-21 2 views
0

Ich versuche ein iOS zu erstellen, wo ich alle x Sekunden meinen Standort aktualisieren und eine Benachrichtigung senden kann, um die Benutzeroberfläche zu aktualisieren. Ich bekomme meinen Standort, aber das Update ist zufällig. Irgendwelche Ideen, wie man das Intervall hinzufügt?Update-Standort alle x Sekunden iOS

hier ist mein Code:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
{ 
    CLLocation *location = [locations lastObject]; 
    [self sendNotification :@"long" 
          :[NSString stringWithFormat:@"%.8f",location.coordinate.longitude]]; 
    [self sendNotification :@"lat" 
          :[NSString stringWithFormat:@"%.8f",location.coordinate.latitude]]; 

} 
+0

Warum alle x Sekunden aktualisieren, wenn der Standortmanager Sie nur informieren kann, wenn der Standort geändert wurde. – rckoenes

+0

Ich brauche es in einem Intervall, auch wenn es nicht geändert wurde –

+0

Nun, das ist nicht, wie CoreLocation funktioniert. Also wirst du es fälschen müssen. Speichere den letzten Ort in einer Variablen und lies dies alle x Sekunden ab. – rckoenes

Antwort

0

Verwendung NSTimer:

// global deklarieren

NSTimer *ShareTimeCheck; 
    int ShareSecLeft; 

diese Methode implementieren:

-(void)shareTimeChecking{ 
     if (ShareSecLeft==0) { 
      [ShareTimeCheck invalidate]; 
      ShareTimeCheck=nil; 
     }else{ 
      ShareSecLeft--; 
      if (ShareSecLeft==0) { 
       [ShareTimeCheck invalidate]; 
       ShareTimeCheck=nil; 
      } 
     } 
    } 

Aufruf dieses in ur Location Update-Methode:

    if (ShareSecLeft==0) { 
     [ShareTimeCheck invalidate]; 
         ShareTimeCheck=nil; 
         ShareSecLeft=5; 

    heduledTimerWithTimeInterval:1 target:self selector:@selector(shareTimeChecking) userInfo:nil repeats:YES]; 

    //write ur code to update the ui. or update to server as per ur requirement. 

} 
+0

Sorry, aber es hat nicht funktioniert –

+0

Kann ich jetzt was ist das Problem ...? Ich eine Aktualisierung alle 5 Sekunden in meiner Anwendung .. es funktioniert gut für mich ... –

0

In iOS nativ können wir nicht das Intervall ändern, bei dem das System den Standort des Nutzers. IOS aktualisiert die Position regelmäßig jede Sekunde, wenn GPS-Signal vorhanden ist.

Wenn die Anwendung im Vordergrund ist, können wir die Überwachung einfach stoppen und nach einem Intervall erneut starten, z. B. mit NSTimer. In diesem Fall müssen wir über das Leben der Anwendung nachdenken. Die Anwendung wird im Hintergrund ausgeführt und während des Leerlaufs nicht mehr ausgeführt.

Meine letzte Prozedur ist NSTimer im Hintergrund verwenden mit UIApplication:beginBackgroundTaskWithExpirationHandler:. Dieser Timer wird regelmäßig ausgelöst, während die Anwendung im Hintergrund ausgeführt wird. Sie können das folgende Beispiel an:

#import "AppDelegate.h" 

@implementation AppDelegate 

BOOL locationStarted = FALSE; 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    //set default value after application starts 
    locationStarted = FALSE; 
    //create CLLocationManager variable 
    locationManager = [[CLLocationManager alloc] init]; 
    //set delegate 
    locationManager.delegate = self; 

    app = [UIApplication sharedApplication]; 

    return YES; 
} 

//update location 
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ 
    NSLog(@"Location: %f, %f", newLocation.coordinates.longtitude, newLocation.coordinates.latitude); 
} 

//run background task 
-(void)runBackgroundTask: (int) time{ 
    //check if application is in background mode 
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) { 

     //create UIBackgroundTaskIdentifier and create a background task, which starts after time 
     __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
      [app endBackgroundTask:bgTask]; 
      bgTask = UIBackgroundTaskInvalid; 
     }]; 

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
      NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(startTrackingBg) userInfo:nil repeats:NO]; 
      [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode]; 
      [[NSRunLoop currentRunLoop] run]; 
     }); 
    } 
} 

//starts when application switches to background 
- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    //check if application status is in background 
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) { 
     NSLog(@"start background tracking from appdelegate"); 

     //start updating location with location manager 
     [locationManager startUpdatingLocation]; 
    } 

    //change locationManager status after time 
    [self runBackgroundTask:20]; 
} 

//starts with background task 
-(void)startTrackingBg{ 
    //write background time remaining 
    NSLog(@"backgroundTimeRemaining: %.0f", [[UIApplication sharedApplication] backgroundTimeRemaining]); 

    //set default time 
    int time = 60; 
    //if locationManager is ON 
    if (locationStarted == TRUE) { 
     //stop update location 
     [locationManager stopUpdatingLocation]; 
     locationStarted = FALSE; 
    }else{ 
     //start updating location 
     [locationManager startUpdatingLocation]; 
     locationStarted = TRUE; 
     //ime how long the application will update your location 
     time = 5; 
    } 

    [self runBackgroundTask:time]; 
} 

//application switches back from background 
- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    locationStarted = FALSE; 
    //stop updating 
    [locationManager stopUpdatingLocation]; 
} 

/*** other methods ***/ 
- (void)applicationWillResignActive:(UIApplication *)application{} 

- (void)applicationDidBecomeActive:(UIApplication *)application{} 

- (void)applicationWillTerminate:(UIApplication *)application{} 

@end 

Eine einfachere Lösung könnte sein, die Timer-Schleife auszuführen:

__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
    [app endBackgroundTask:bgTask]; 
    bgTask = UIBackgroundTaskInvalid; 
}]; 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
    NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(startTrackingBg) userInfo:nil repeats:YES]; 
    [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode]; 
    [[NSRunLoop currentRunLoop] run]; 
}); 
+0

Was ist die Variable App? –

+0

chogath Entschuldigung, ich habe vergessen, den AppDelegate.h Code hinzuzufügen. @interface AppDelegate: UIResponder { CLLocationManager * locationManager; UIApplication * app; } –

+0

Ich habe ein neues Projekt erstellt und ich habe Ihren Code kopiert und nichts wird in der Konsole angezeigt! –

0

Try this:

in .h-Datei deklariert

@property (strong, nonatomic) NSDate *lastTimestamp; 

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
{ 
    CLLocation *mostRecentLocation = locations.lastObject; 
    NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude)); 

    NSDate *now = [NSDate date]; 
    NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0; 

    if (!self.lastTimestamp || interval >= 5 * 60) 
    { 
     self.lastTimestamp = now; 
     NSLog(@"update your UI"); 
    } 
} 
Verwandte Themen