[swift] 現在のアプリのバージョンを出力・比較してアップロードを促す
目次
現在のアプリのバージョンを出力・比較してアップロードを促す
現在のアプリのバージョンを出力するには
NSBundle.mainBundle().objectForInfoDictionaryKey(“CFBundleShortVersionString”)
NSBundle.mainBundle().objectForInfoDictionaryKey(“CFBundleVersion”)
で出力できる
Stringで出力されるので、バージョン比較するときはFloatなどに変換するとよい
現在のアプリのバージョンを出力
let current: String! = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let build: String! = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as String print("current version is \(Float(current)!)") print("current build is \(Float(build)!)")
Swift4
Swift4では以下のコード
let version: String! = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let build: String! = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
バージョンを比較してアップロードを促す
let latest = 2.111111 //本来はどこかのDBかサーバから最新バージョン情報を取得すべき override func viewDidLoad() { super.viewDidLoad() let current: String! = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let build: String! = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as String print("current version is \(Float(current)!)") print("current build is \(Float(build)!)") if(latest>Float(current)){ _showDialog() } } func _showDialog(){ let title = "新しいバージョン" let message = "新しいバージョンがリリースされています、アップロードをお願いします。" let alert = UIAlertController(title:title, message: message, preferredStyle: UIAlertControllerStyle.Alert) let OKAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (action:UIAlertAction!) -> Void in self._openItuneStore() }) alert.addAction(OKAction) self.presentViewController(alert, animated: true, completion: nil) } func _openItuneStore(){ let itunesURL:String = "itms-apps://itunes.apple.com/app/xxxxxxx" //xxxxxxはアプリID let url = NSURL(string:itunesURL) let app:UIApplication = UIApplication.sharedApplication() app.openURL(url!) }