9
6

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] 端末のバージョンを比較

Last updated at Posted at 2017-10-16

端末のバージョンを比較

アプリに重大なバグが見つかった時など,アプリ起動時にアップデート通知をしたいですよね.何が起こるか分からないので,appStoreにアップロードする前に,実装しておきたいところです.端末のバージョンと最新のバージョンの比較メソッドは,今後いつも使うと思うのでメモとして残しておきます.

ビルドのバージョンを取得

以下のコードで,buildのバージョンを取得できます.
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String

最新のバージョンと比較

最新のbuildバージョンをサーバーから取ってきたとします.splitして比較してあげたら楽ですね.

version.swift
enum currentVersionStatus {
    case lastest
    case old
    case error
}

func compareVersion(lastest: String, current: String) -> currentVersionStatus {
    let lastest_split = lastest.components(separatedBy: ".")
    let current_split = current.components(separatedBy: ".")
    for (l, c) in zip(lastest_split, current_split) {
        if let lastInt = Int(l), let currentInt = Int(c) {
            if currentInt < lastInt { return .old }
            else if currentInt > lastInt { return .lastest }
        } else { return .error }
    }
    return .lastest
}

let lastestVersion = "2.0.5"
let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
compareVersion(lastest: lastestVersion, current: currentVersion)

// example
compareVersion(lastest: "1.0.5", current: "1.0.2") // => old
compareVersion(lastest: "2.0.5", current: "1.0.10") // => old
compareVersion(lastest: "2.1.3", current: "2.1.3") // => lastest
compareVersion(lastest: "3.1.7", current: " ") // => error

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?