2015-06-05 59 views
0

當我的用戶更改位置時,我需要將他的位置與從網絡中拉出的位置數組進行比較。然而,在我的appDelegate中,我不確定究竟在哪裏放置我的代碼,因爲我不確定當應用程序終止時調用或未調用哪些方法,但CLLocationManager仍然有效。在終止應用程序時在DidUpdateLocations中進行Web通話

具體來說,我需要輸入這個代碼,它實際上將被調用時,應用程序還是終止:

// 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

處理位置更新,當您的應用程序在後臺,甚至終止,您可以使用「顯着位置更改」 。當位置發生顯着變化時,它將觸發應用程序以背景模式啓動。然後,您可以開始後臺任務,根據需要執行操作。

文檔: 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

相關問題