2013-02-03 126 views
2

我有一個應用程序與區域監控時運行幾分鐘,GPS,但爲了更好的presition我打電話「startUpdatingLocation」使用的GPS,當用戶進入指定的區域:按住Home鍵

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region { 
    [manager startUpdatingLocation]; 
} 



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

    CLLocation *location1 = locationManager.location; 
    CLLocation *location2 = [[CLLocation alloc] initWithLatitude:obj.latitude longitude:obj.longitude]; 
    float betweenDistance=[location1 distanceFromLocation:location2]; 


    if((betweenDistance/1000)<=0.350000){ 
      // Fires an UIAlert 
    } 

}

,如果用戶是該地區以外,然後按「主頁按鈕」,進入該區域後,觸發功能「didEnterRegion」和GPS開始工作在大多數情況下,精細,例如工作幾分鐘,並顯示警報,這是正確的方法。

但是,如果應用程序是打開的,然後用戶在該地區輸入火災功能「didEnterRegion」,並開始GPS,但如果用戶在此時按下「主頁按鈕」,GPS停止並且警報不會出現。

我不想激活info.plist中的「所需的背景模式」選項,因爲我只想在用戶按下de Home按鈕之後使用GPS幾分鐘,而不是用於在excesive模式。

任何想法?

回答

2

當你的應用程序委託得到消息applicationWillResignActive:您可以請求操作系統讓你的應用程序運行通過創建這樣一個請求:

UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
    // do you cleanup in here if your background task gets terminated by the system 
}]; 

之後,你的事件循環將繼續運行,你會繼續接收正常的事件(除非您的應用程序的窗口不可見,所以您顯然不會收到觸摸事件或其他窗口相關事件)。

一旦你不再需要保持運行,你可以釋放你的要求是這樣

[[UIApplication sharedApplication] endBackgroundTask:taskID]; 

爲了讓所有的工作,只需添加一個標誌,你的應用程序代理,讓它知道當你做需要更多時間的東西。然後,當您的委託獲取applicationWillResignActive:消息時,它可以檢查該標誌,並且如果它已設置,請求一些背景時間以繼續運行。

+0

謝謝,但我的CLLocationManager委託是在另一個視圖中,我需要調用同一個CLLocationManager的方法「startUpdatingLocation」,直到用戶獲得你的命運。我不知道如何在AppDelegate中的「applicationWillResignActive」中執行此操作。 –

+0

後臺任務的東西只是告訴系統保持你的應用程序運行。無論您的CLLocationManager位於何處,都只需與應用程序委託人溝通,以確保應用程序需要保持活動一段時間,然後委託人可以告知系統何時應用程序被要求辭職。 –