簡體   English   中英

如果用戶在應用程序處於后台時進入/退出區域,則調用localNotification

[英]Call a localNotification if user enters/exits region while app is in background

如果用戶在應用程序處於后台模式時進入或退出區域,我需要執行調用localNoification的簡單任務。 只有一組坐標會觸發通知。 例如:

緯度:41.8500弧度:87.6500半徑:300

我知道如何調用localNotification,以及如何使用locationManager的基本功能,但似乎無法在后台跟蹤位置。 任何幫助將是巨大的!

您是否閱讀過CLLocationManager的startMonitoringForRegion:方法? 我認為這完全可以滿足您的需求。 設置它的代碼如下所示:

CLRegion * region = [[CLRegion alloc] initCircularRegionWithCenter: CLLocationCoordinate2DMake(41.8500, 87.6500) radius: 300 identifier: @"regionIDstring"];
CLLocationManager * manager = [[CLLocationManager alloc] init];
[manager setDelegate: myLocationManagerDelegate];
[manager startMonitoringForRegion: region];

之后,即使您的應用程序在后台,設備也會監視指定區域的出入口。 跨區域時,代表將收到呼叫locationManager:didEnterRegion:locationManager:didExitRegion: 您可以利用此機會發布UILocalNotification 如果您的應用程序在跨區域時未運行,它將在后台啟動,您將需要在application: didFinishLaunchingWithOptions:查找適當的密鑰application: didFinishLaunchingWithOptions: 使用如下代碼:

if ([launchOptions objectForKey: UIApplicationLaunchOptionsLocationKey] != nil) {
    // create a location manager, and set its delegate here
    // the delegate will then receive the appropriate callback
}

請注意,在后台運行時,該應用只有很短的執行時間(幾秒鍾); 如果您需要執行更長的任務,請在應用程序收到區域交叉通知后立即調用beginBackgroundTaskWithExpirationHandler:在其答案中提到的beginBackgroundTaskWithExpirationHandler:方法。 這將使您在后台運行約600秒。

看看UIApplicationbeginBackgroundTaskWithExpirationHandler:方法。 當應用程序在后台運行時,它允許您請求額外的時間來運行任務。

有關更多信息,建議您閱讀iOS應用程序編程指南中的“ 后台執行和多任務處理 ”部分。 它詳細說明了當應用程序在后台運行時會發生什么以及允許您做什么。

具體來說,它顯示了該示例在后台運行時運行長時間任務的示例代碼:

[ 此代碼取自上面鏈接的Apple指南 ]

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you.
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM