2016-11-15 18 views
1

私はこのコードをここにあります。今私はシングルトンでそれを使う方法を知りたいです。私が理解しているのは、シングルトンでこのコードを使用すると、ネットワークの状態が変化した場合に気付かれるでしょう。このコードを迅速にシングルトンで使用するにはどうすればよいですか?

func startNetworkReachabilityObserver() { 
    let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com") 
    reachabilityManager?.listener = { status in 

     switch status { 

     case .NotReachable: 
      print("The network is not reachable") 

     case .Unknown : 
      print("It is unknown whether the network is reachable") 

     case .Reachable(.EthernetOrWiFi): 
      print("The network is reachable over the WiFi connection") 

     case .Reachable(.WWAN): 
      print("The network is reachable over the WWAN connection") 

     } 
    } 

    // start listening 
    reachabilityManager?.startListening() 
} 
+0

単にクラスメソッドにしてそのまま使用することができます。私が推測するシングルトンを使う必要はありません。アプリケーションが起動するとすぐにこの関数を呼び出してください。 – Adeel

+0

他のクラスと同じようにシングルトンで使用しても差はありませんが、シングルトンには魔法はありません。シングルトンに入れなければならないということです。クラスの寿命は通知変更が必要な限り長くなります。 – Gruntcakes

+0

クラスメソッドを作成した場合、ネットワークステータスの変更は通知されません。シングルトンで私はそうするでしょう。 – FoG

答えて

0

変数をプロパティとしてクラスに持ち込む。クラスをシングルトンにするために静的な共有プロパティを追加します。静的プロパティは、デフォルトでは怠け者です

class ReachabilityManager { 
     private let networkReachabilityManager = NetworkReachabilityManager() 
     static let shared = ReachabilityManager() 
     private override init() { 
      super.init() 
      networkReachabilityManager?.listener = { status in 
       //Post Notifications here 
       } 
      } 
     } 
     func startListening() { 
      networkReachabilityManager.startListening() 
     } 
    } 

ので、あなたがReachabilityManager.shared.startListening(呼び出す)それは初めてシングルトンのインスタンスを作成し、後続の呼び出しは、既存の共有インスタンスを使用します。あなたが通知されます

let networkStatus = NetworkStatus.sharedInstance 

override func awakeFromNib() { 
    super.awakeFromNib() 
    networkStatus.startNetworkReachabilityObserver() 
} 

:私は長い間、あなたがreachabilityManager

class NetworkStatus { 
static let sharedInstance = NetworkStatus() 

private init() {} 

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com") 

func startNetworkReachabilityObserver() { 
    reachabilityManager?.listener = { status in 

     switch status { 

     case .notReachable: 
      print("The network is not reachable") 

     case .unknown : 
      print("It is unknown whether the network is reachable") 

     case .reachable(.ethernetOrWiFi): 
      print("The network is reachable over the WiFi connection") 

     case .reachable(.wwan): 
      print("The network is reachable over the WWAN connection") 

     } 
    } 
    reachabilityManager?.startListening() 
} 

}

だから、あなたはこのようにそれを使用することができますの参照を保持としてとしてシングルトンを使用して

+0

'init'を' private'にして、複数のシングルトンオブジェクトをインスタンス化できないようにしてください。 – shallowThought

+0

良いキャッチ私はサンプルコードを更新しました。 –

1

が働いていますあなたのネットワーク状態の変化の

関連する問題