8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:アプリのバージョンアップ直後のみ特定の処理を実行させる

8
Last updated at Posted at 2019-02-16

概要

アプリを頻繁にアップデートする開発者ならば,アップデート直後のみに特定の処理を実行させたくなる時があると思います.そんな時に役立つコードを考えてみました.

ソース

let userDefaults = UserDefaults.standard

private func settingJustAfterUpdating() {
    let dicKey = "CFBundleShortVersionString"
    guard let version = Bundle.main.object(forInfoDictionaryKey: dicKey) else { return }
    let newVersionKey = "ver\(version as! String)"
    // 初回起動時のみ処理が呼ばれるようにフラグを立てる
    userDefaults.register(defaults: [newVersionKey : true])
    // もしも最新バージョンでのアプリ起動が初めてならば
    if userDefaults.bool(forKey: newVersionKey) {
        // 次回起動以降は処理が呼ばれなくなるようにフラグを折る
        userDefaults.set(false, forKey: newVersionKey)

        // ここでアップデート直後のみ行なわせたい処理を呼び出す

        // 不要となった過去バージョンにおけるフラグをUserDefaultsから削除する
        // verから始まる名前のキーが他の用途向けに無いよう設計に注意!
        if let dataList = userDefaults.persistentDomain(forName: Bundle.main.bundleIdentifier!) {
            let versionKeys = dataList.compactMap { $0.key.hasPrefix("ver") ? $0.key : nil }
            versionKeys.forEach { (key) in
                userDefaults.removeObject(forKey: key)
            }
        }
    }
}

// ViewDidLoad()内部とかで呼ぶ
settingJustAfterUpdating()
8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?