LoginSignup
2
3

More than 3 years have passed since last update.

[Swift] iOSのBackground Fetchとアプリのアイコンの変更を試す

Last updated at Posted at 2019-05-04

iOS 10.3からアプリのアイコンを動的に変更できるようになったらしい(WatchやCalenderのように)。そこで、アプリを起動せず、アイコンだけで状態を表すをアプリを作りたい。一つの案はBacground Fetch機能と組み合わせ、アプリのアイコンを変更することだと思い、調べた結果をまとめた。

結論からいうと、できなかった!

実行環境

  • macOS Mojave
  • Swift 5
  • iOS 12.2

簡単なアプリとBackground Fetchサポートを設定する

まず、Xcode使い、簡単アプリのプロジェクトを作成する。このアプリのデフォルトのアイコンが↑の画像で、Alternateボタンを押せば、アプリのアイコンが↓になる。

次に、プロジェクトの設定でBackground Fetchのケイパビリティを有効にする。
スクリーンショット 2019-05-05 2.22.49.png

Background Fetchの動作

動的にアイコンを変えるために、参考資料のように2つの画像を準備し、Info.plistを編集する

スクリーンショット 2019-05-05 2.52.31.png

AppDelegate.swift を以下のようにBackground Fetchを実装する。その内容はAlternateボタンが押された時と同じ内容である。

AppDelegate.swift

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

        return true
    }
    func application(_ application: UIApplication,
                     performFetchWithCompletionHandler completionHandler:
        @escaping (UIBackgroundFetchResult) -> Void) {

        print("Background fetch activated")
        // change icon
        application.setAlternateIconName("AlternateIcon"){ error in
            if let error = error {
                print("Error!")
                print("Error:" + error.localizedDescription)
            } else {
                print("Done!")
            }
        }
        completionHandler(.noData)
    }

実行した結果

アプリがフォアグランドの場合

アプリが実行する状態で、DebugからBackground Fetchを開始する
スクリーンショット 2019-05-05 3.06.43.png

アプリおよびログからアイコンが正しく変更されたことが確認できた
スクリーンショット 2019-05-05 3.11.10.png

アプリがバックグランドの場合(やりたいこと!)

次に、アプリがバックグランドの状態で、同じくBackground Fetchを開始する。今回、アプリのアイコンが変わらず、それに、 The operation was cancelledのエラーが出力された。
スクリーンショット 2019-05-05 3.17.15.png

まとめ

Background Fetchの機能および動的にアプリのアイコンを組み合わせして試したが、残念ながらうまく動かなかった。どうやらWatchやCalendarのようにできず、OSから禁止されたように見える。今後、やりたいことは他の方法で探してみたいと思う。


参考する情報
- 動的にアプリのアイコンを変更する
- Appleからの情報

2
3
0

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
2
3