古詩詞大全網 - 成語查詢 - ios background fetch 多久執行壹次

ios background fetch 多久執行壹次

關於Background Fetch的更多請參考:<IOS 7四種後臺機制> 中關於Background Fetch的解釋,這裏只說明怎麽使用Background Fetch。

壹,開啟Background Fetch支持

在XCode->TARGETS->Capabilities->Background Modes打開並添加Background Fetch.

同時在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加:

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

MinimumBackgroundFetchInterval參數值是兩次Fetch時間間隔,不能保證每隔這個時間間隔都會調用。這裏設置為UIApplicationBackgroundFetchIntervalMinimum,意思是盡可能頻繁的調用我們的Fetch方法。

二,增加實現Fetch方法

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{};

每次系統Fetch時都會調用該方法,我們可以在該方法中做刷新數據等操作,操作執行完成以後要調用completionHandlerblock(),比如:completionHandler(UIBackgroundFetchResultNewData);文檔中說系統會根據completionHandler(執行的時間)來估計此次Fetch的耗電等。如果耗時耗電比較多,可能會降低被調用的次數。但這個方法也不是不限時執行的,說是有30s的時間來執行操作。completionHandler有三個參數:

UIBackgroundFetchResultNewData 成功拉取數據

UIBackgroundFetchResultNoData 沒有新數據

UIBackgroundFetchResultFailed 拉取數據失敗或者超時

三,模擬Fetch事件

在實際的IOS7環境中,Fetch事件是由系統管理的,app開發者無法預先知道Fetch事件達到的時機。但XCode也提供了Fetch事件的調試辦法,在XCode上運行程序後,在Debug->Simulate Background Fetch.

還有壹種情況是app沒有運行(不在前臺也不在後臺),被Fetch事件喚醒執行.這種情況的測試方法如下:

Product->Scheme->Edit scheme 在Debug模式選中Options,點選Launch due to a background fetch event,運行即可。

[特酷吧]可以觀察到當Fetch事件到來時,app先進入後臺,再執行- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{}。

四,判斷設備是否開啟後臺應用程序刷新功能

折疊C/C++ Code復制內容到剪貼板

if ([[UIApplication sharedApplication] backgroundRefreshStatus] != UIBackgroundRefreshStatusAvailable)

{

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您沒有開啟後臺刷新,請在 設置->通用->應用程序後臺刷新 中開啟." delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

[alertView show];

[alertView release];

}