LoginSignup
10

More than 5 years have passed since last update.

(Swift)iOSアプリが最新のバージョンであるかを確認する

Last updated at Posted at 2017-03-22

はじめに

アプリのバージョンがAppStoreのバージョンと比較して、最新のバージョンであるかを確認する方法について記載しました。
例えば旧バージョンの場合はAppStoreに誘導したい場合などに使えるかと思います。

コード

Apple ID(アプリのID)を渡すと結果(AppVersionCompareType)が返ってきます。

AppVersionCompare.swift
import Foundation

enum AppVersionCompareType {
    case latest
    case old
    case error
}

class AppVersionCompare {
    static func toAppStoreVersion(appId: String, completion: @escaping (AppVersionCompareType) -> Void) {
        guard let url = URL(string: "https://itunes.apple.com/jp/lookup?id=\(appId)") else {
            completion(.error)

            return
        }

        let request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
            guard let data = data else {
                completion(.error)

                return
            }

            do {
                let jsonData = try JSONSerialization.jsonObject(with: data) as? [String: Any]
                guard let storeVersion = ((jsonData?["results"] as? [Any])?.first as? [String : Any])?["version"] as? String
                    , let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String else {
                        completion(.error)

                        return
                }

                switch storeVersion.compare(appVersion, options: .numeric) {
                case .orderedDescending:
                    //appVersion < storeVersion
                    completion(.old)
                case .orderedSame, .orderedAscending:
                    //storeVersion <= appVersion
                    completion(.latest)
                }
            }catch {
                completion(.error)
            }
        })

        task.resume()
    }
}

使い方

下記のように使います。

viewDidLoad
        AppVersionCompare.toAppStoreVersion(appId: appId) { (type) in
            switch type {
            case .latest:
                print("最新バージョンです")
            case .old:
                print("旧バージョンです")
            case .error:
                print("エラー")
            }
        }

下記のアプリバージョン(Version この場合2.0.0)とAppStoreバージョンを比較しています。
スクリーンショット 2017-03-22 20.48.17.png

最後に

GitHubにコードを置いています。
https://github.com/hideyukitone/AppVersionCompare

参考
http://qiita.com/usatie/items/5f8a1f1f41a58f9e0035

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
10