iOSにおけるバックグラウンド処理の一つ、Background Fetchを実装する方法。
Capabilitiesの変更
プロジェクトの設定からCapabilitiesを開き、Background ModeをONにして、中にあるBackground fetchにチェックを入れます。
コード
AppDeligateに以下のコードを加えます。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
// background fetch
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
...
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// background fetchの処理
println("background fetch is called!")
// 最後に呼ぶ必要がある
completionHandler(UIBackgroundFetchResult.NewData)
}
簡単な解説
AppDeligateの初期化時に設定しているapplication.setMinimumBackgroundFetchIntervalは、Background Fetchの実行頻度です。
ここでは定数のUIApplicationBackgroundFetchIntervalMinimumを設定しています。
Background Fetchは最低でもこの間隔を開けて実行されることになります。
Background Fetchの本体は、performFetchWithCompletionHandlerです。
ここに実際の具体的な処理を記述します。
performFetchWithCompletionHandlerは、引数にとるcompletionHandlerを実行する必要があります。
これは、OSが返された値を元に、アプリが使用したプロセス時間・電力消費などを判断し、以降のSilent PushやBackground Fetchの頻度に反映させるために用いられるようです。引数に渡すべき値(UIBackgroundFetchResult.NewData, .NoData, .Failed)の詳細についてはリンク先を見てください。


