MILLEN BOX

音楽好きの組み込みソフトエンジニアによるプログラミング(主にiOSアプリ開発)の勉強の記録

iOSバージョンによって異なった処理でアラートを表示する [swift1.2] [UIDevice] [UIAlertController][UIAlertView]

2015年9月10日(日本時間)ですこんにちは。
Appleから色々発表があった日に更新するような記事ではない気が激しくしますが更新します。
マイペースを突き進みます。

アラートの表示を行った方が良さそうな箇所が出てきたため調べてみると、iOS7まで広く使われていたUIAlertViewはiOS8以降は非推奨となり、その変わりにUIAlertControllerというクラスを使用することが推奨となったことを知りました。
そうなると、iOS7以降の複数のiOSをサポートするアプリを作成する場合、実行したiOSのバージョンによって処理を変更したくなります。
ということで、今回は

  • iOSバージョンの取得
  • iOS7以前の場合にはUIAlertViewでアラート処理
  • iOS8以降の場合にはUIAlertControllerでアラート処理

を行いたいと思います。
f:id:anthrgrnwrld:20150910201458g:plain

Githubは以下です。

GitHub - anthrgrnwrld/alert

また以下の記事を参考(時々写経)にしました。

iOSのバージョン判定(Swift) [UIDevice, #available] iOS Objective-C, Swift Tips-モバイル開発系(K)

UIAlertViewでポップアップ表示 - Swiftサラリーマン

Swift:UIAlertController でアラートを表示するサンプルコード | siro:chro

自分ポイント1

iOSバージョンの取得 ですが、 UIDeviceクラスcurrentDeviceメソッド 内、systemVersionプロパティにて取得可能です。

let iOSVersion: NSString! = UIDevice.currentDevice().systemVersion as NSString
println("iOSVersion is \(iOSVersion)")   //取得結果を一応printしときますね

自分ポイント2

今回のようにiOS7とiOS8で壁を作成する場合には以下のような記載になります。
取得したバージョン入ったプロパティに対し、 .floatValueを用いることでバージョンの数値のみ取り出せることがポイントです。

//iOSのバージョンを取得        
let iOSVersion: NSString! = UIDevice.currentDevice().systemVersion as NSString
println("iOSVersion is \(iOSVersion)")
        
//iOS Verによってアラート動作を変える
if iOSVersion.floatValue < 8.0 {      //.floatValueを用いることでバージョン数値のみをfloat型で取り出せる
    //iOS7用のアラート表示処理を書く (UIAlertViewを使用)
} else {
    //iOS8用のアラート表示処理を書く (UIAlertControllerを使用)
}
        

自分ポイント3

UIAlertViewのアラート処理を行う関数は以下のようになります。
詳細はUIAlertViewでポップアップ表示 - Swiftサラリーマンを見てもらうのがよいかと。
そんなに難しくないです。眺めていれば大体やってること理解できると思います。

    func showAlertIOS7() {
        let alert = UIAlertView()
        alert.title = "alert"
        alert.message = "alertController"
        alert.addButtonWithTitle("Default")
        alert.addButtonWithTitle("Destructive")
        alert.addButtonWithTitle("Cancel")
        alert.show();
    }

自分ポイント4

UIAlertControllerのアラート処理を行う関数は以下のようになります。
詳細はSwift:UIAlertController でアラートを表示するサンプルコード | siro:chroを見てもらうのがよいかと。
これもそんなに難しくないと思います。

    func showAlertIOS8() {
        
        // Style Alert
        let alert: UIAlertController = UIAlertController(title:"alert",
            message: "alertController",
            preferredStyle: UIAlertControllerStyle.Alert
        )
        
        // Cancel 一つだけしか指定できない
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Cancel")
        })
        
        // Default 複数指定可
        let defaultAction: UIAlertAction = UIAlertAction(title: "Default",
            style: UIAlertActionStyle.Default,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Default")
        })
        
        // Destructive 複数指定可
        let destructiveAction: UIAlertAction = UIAlertAction(title: "Destructive",
            style: UIAlertActionStyle.Destructive,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Destructive")
        })
        
        // AddAction 記述順に反映される
        alert.addAction(cancelAction)
        alert.addAction(defaultAction)
        alert.addAction(destructiveAction)
        
        // Display
        presentViewController(alert, animated: true, completion: nil)
        
    }

自分ポイント5

最後にヌルっと全部書いたソースを貼っておきます。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func pressAlertButton(sender: AnyObject) {
        
        let iOSVersion: NSString! = UIDevice.currentDevice().systemVersion as NSString
        println("iOSVersion is \(iOSVersion)")
        
        //iOS Verによってアラート動作を変える
        if iOSVersion.floatValue < 8.0 { self.showAlertIOS7() }
        else { self.showAlertIOS8() }
        
    }
    
    func showAlertIOS8() {
        
        // Style Alert
        let alert: UIAlertController = UIAlertController(title:"alert",
            message: "alertController",
            preferredStyle: UIAlertControllerStyle.Alert
        )
        
        // Cancel 一つだけしか指定できない
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Cancel")
        })
        
        // Default 複数指定可
        let defaultAction: UIAlertAction = UIAlertAction(title: "Default",
            style: UIAlertActionStyle.Default,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Default")
        })
        
        // Destructive 複数指定可
        let destructiveAction: UIAlertAction = UIAlertAction(title: "Destructive",
            style: UIAlertActionStyle.Destructive,
            handler:{
                (action:UIAlertAction!) -> Void in
                println("Destructive")
        })
        
        // AddAction 記述順に反映される
        alert.addAction(cancelAction)
        alert.addAction(defaultAction)
        alert.addAction(destructiveAction)
        
        // Display
        presentViewController(alert, animated: true, completion: nil)
        
    }
    
    func showAlertIOS7() {
        let alert = UIAlertView()
        alert.title = "alert"
        alert.message = "alertController"
        alert.addButtonWithTitle("Default")
        alert.addButtonWithTitle("Destructive")
        alert.addButtonWithTitle("Cancel")
        alert.show();
    }

}

「バージョンによって処理を変更する」とか何かかっこいいな〜と思っています。