应用程序终止时,DidUpdateLocations中的Web调用

时间:2015-06-05 19:12:24

标签: ios cllocationmanager appdelegate

当我的用户更改位置时,我需要将他的位置与我从网络上提取的一系列位置进行比较。但是,在我的appDelegate中,我不确定在何处放置我的代码,因为我不确定在应用程序终止时调用或未调用的方法,但CLLocationManager仍然有效。

具体来说,我需要在应用程序仍然终止时实际调用此代码:

// alloc and init the various (Mutable)Array properties
self.locations = [[NSMutableArray alloc] init];

// Create new HomeModel object and assign it to _homeModel variable
_homeModel = [[DealsModel alloc] init];

// Set this view controller object as the delegate for the home model object
_homeModel.delegate = self;

// Call the download items method of the home model object
[_homeModel downloadItems];

_homeModel将调用此方法:

-(void)itemsDownloaded:(NSArray *)items
{
    // This delegate method will get called when the items are finished downloading

    // Set the downloaded items to the array
    _locations = [items copy];
}

我将进一步编辑以将用户的位置与位置数组进行比较。

问题是,这一系列的地点每周只会改变一次。每当用户的位置发生变化时,应用程序是否真的必须从网上提取它?或者有没有办法缓存这个,只有在self.locations被释放后才拉出它?

这就是我现在所拥有的,但我觉得必须有更好的方法:

@interface AppDelegate () <CLLocationManagerDelegate>
{
    DealsModel *_homeModel;
}

@property BOOL didRunBefore;
@property CLLocationManager *locationManager;
@property NSMutableArray *deals;

@end

@implementation AppDelegate

-(void)itemsDownloaded:(NSArray *)items
{
    // This delegate method will get called when the items are finished downloading

    // Set the downloaded items to the array
    _deals = [items copy];
    [self compareSponsorLocations:_deals toUserLocation:[self.locationManager location]];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {

    if (!self.deals) {
    // alloc and init the various (Mutable)Array properties
    self.deals = [[NSMutableArray alloc] init];

    // Create new HomeModel object and assign it to _homeModel variable
    _homeModel = [[DealsModel alloc] init];

    // Set this view controller object as the delegate for the home model object
    _homeModel.delegate = self;

    // Call the download items method of the home model object
    [_homeModel downloadItems];
    } else {
    [self compareSponsorLocations:self.deals toUserLocation:[locations lastObject]];
    }
}

- (void) compareSponsorLocations: (NSArray *) array toUserLocation: (CLLocation *) location
{
    for (Deal *deal in array) {
        NSLog(@"%@", deal.name);
    }
    NSLog(@"%@", location.description);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...

1 个答案:

答案 0 :(得分:1)

要在应用处于后台或终止时处理位置更新,您可以使用&#34;重要位置更改&#34;。当位置发生显着变化时,它将触发应用程序以后台模式启动。然后,您可以启动后台任务来执行您需要的操作。

文档: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW8

模拟和调试的简便方法: XCode / iOS simulator: Trigger significant location change manually