LoginSignup
6
6

More than 5 years have passed since last update.

SwiftのProtocolでTraitを実装する

Posted at

はじめに

今回は趣味で開発しているアプリでTraitを実装することがあったのでそれのアレ

Trait とは 形質

実装し終わったら「あ〜そういう意味か。」というような納得できました。ミックスイン的なやつらしいです。(ミックスインではない)

内容

  • Reachabilityを使って各UIViewControllerでネットワークステータスを確認する
  • ネットワークステータスに変更があればそれに対応した動作をさせる

ざっとこれ

環境

  • 情弱社会人2年目iOSエンジニア
  • Pythonが好き
  • Xcode 8.3.3
  • Swift 3.1
  • macOS Sierra 10.12.4

準備

  • Xcodeプロジェクトの作成
  • ReachabilityをDLして打ち込む 公式
    • 公式のものなのでCocoaPods, Carthageなどで入れたやつとかは知らない!!

サンプル

CustomViewController.swift

import UIKit

class CustomViewController: UIViewController {

    fileprivate var reachability = Reachability.forInternetConnection()

    override func viewDidLoad() {
        super.viewDidLoad()
        reachability?.startNotifier()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChange(_:)), name: NSNotification.Name.reachabilityChanged, object: nil)
    }

    deinit {
        reachability?.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.reachabilityChanged, object: nil)
    }

    ・・・

    // MARK: - Reachability's notification target method

    func networkStatusChange(_ sender: Notification) {
        let networkStatus = reachability?.currentReachabilityStatus()
        if networkStatus == NotReachable {
            return
        }
        something()
    }
}

// MARK: - ReachabilityStatusChange

extension CustomViewController : ReachabilityStatusChange {}

だいたいこんな感じの内容

今回はオンラインになったときに以下で作成する something() メソッドを呼び出す形

UIViewController+Reachability.swift

とりあえずクラス拡張としてファイルを生成しました。

import UIKit

protocol ReachabilityStatusChange {
    func something()
}

// これをコメントインした場合は、すべてUIViewControllerに反映される
// extension UIViewController : ReachabilityStatusChange {}

extension ReachabilityStatusChange where Self : UIViewController {

    func something() {
        print("オンラインになった!")
    }
}

最後に

これですべて動作させたいクラスファイルに関して something() メソッドの実装を書くことがなくなった。幸せになれた。

何か間違い等あればご指摘いただけると幸いです:;(∩´﹏`∩);:

6
6
1

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