LoginSignup
38

More than 5 years have passed since last update.

(iOS)Background fetchの実装方法

Last updated at Posted at 2017-03-12

Background fetchとは

アプリを起動していなくても、OSの判断で適切だと思われるタイミングで、任意の処理をバックグランドで実行することができます。

手順1 Background fetchの有効化

Capabilities → Background Modes → Background fetchをオンにします。
スクリーンショット 2017-03-12 15.13.35.png

手順2 任意の処理を実行する間隔の指定

AppDelegate.swiftのdidFinishLaunchingWithOptionsに
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
を実装する。

※ UIApplicationBackgroundFetchIntervalMinimumとしてもOSの判断で処理が呼ばれるため、常に呼ばれるわけではありません。

AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)

    return true
}

手順3 バックグラウンドで実行する処理の実装

処理を実装します。
処理が終わったらcompletionHandlerを実装する必要があります。
約30秒間猶予を与えられているので、この間に処理を完了させcompletionHandlerを呼べるようにしましょう。
もしcompletionHandlerが呼ばれなかった場合は、次回バックグラウンドで呼ばれる時の間隔に影響するみたいです。

AppDelegate.swift
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    //バックグラウンドで実行する処理

    //適切なものを渡します  新規データ: .newData 失敗: .failed データなし: .noData
    completionHandler(.newData)
}

デバッグ方法①

Edit Scheme...から下記をひらき、Background FetchのLaunch due to a background fetch eventにチェックを入れます。
これで実行するとperformFetchWithCompletionHandlerが呼ばれます。
スクリーンショット 2017-03-12 16.03.15.png

デバッグ方法②

Debug → Simulate Background Fetchを選択するとperformFetchWithCompletionHandlerが呼ばれます。
ただ実機ではなぜかうまくいきませんでした。
スクリーンショット 2017-03-12 16.03.55.png

最後に

自分用のメモとして残しました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38