2016-03-28 22 views
1

在Android系統中,只要系統配置發生變化(例如網絡狀態變化等),系統就會發送廣播。 這些廣播消息可以由我們的應用程序中的broadcastreceiver接收,並相應地更改應用程序的行爲,儘管我們的應用程序未處於運行狀態。 如何在iOS中實現類似的廣播接收器行爲?如何在iOS上獲取非運行狀態下的網絡變化通知

回答

0

您可以使用NSNotificationCenter來監視更改。

NSNotificationCenter.defaultCenter().addObserver(
    self, 
    selector: "batteryLevelChanged:", 
    name: NSUserDefaultsDidChangeNotification, 
    object: nil) 

這裏是API參考: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/

編輯1:

對於你的情況,你可以遵循的步驟和嘗試。

  1. 使用圖書館Reachability得到的 網絡的不斷變化的通知,並定義自定義通知功能。

func reachabilityChanged(note: NSNotification) { 

    let reachability = note.object as! Reachability 

    if reachability.isReachable() { 
    if reachability.isReachableViaWiFi() { 
     print("Reachable via WiFi") 
    } else { 
     print("Reachable via Cellular") 
    } 
    } else { 
    print("Network not reachable") 
    } 
} 
  • 在您的通知功能,創建一個相應的本地 通知

  • var notification = UILocalNotification() 
    notification.alertBody = "Notification message!!!" // text that will be displayed in the notification 
    notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view" 
    notification.fireDate = NSDate() // todo item due date (when notification will be fired) 
    notification.soundName = UILocalNotificationDefaultSoundName // play default sound 
    notification.userInfo = ["UUID": UUID, ] // assign a unique identifier to the notification so that we can retrieve it later 
    notification.category = "CATEGORY" 
    UIApplication.sharedApplication().scheduleLocalNotification(notification) 
    
    +0

    感謝您的回覆。可能是我的問題不清楚。我的期望是在網絡狀態改變時(例如,如果我們從WiFi更改爲數據卡,或者反之亦然),獲取本地通知或者警報或狀態欄上的通知,或者甚至是網絡狀態改變時的通知。即使我的應用程序不處於運行狀態,也應該觸發它。 – user3513902

    +0

    瞭解,那麼你的請求已經有一個庫https://github.com/ashleymills/Reachability.swift。 – BobGao

    +0

    謝謝@ BobGao,我研究了Reachability,它的確如預期的那樣。如果我的應用程序未處於運行狀態,它可以工作嗎?如果我更改網絡狀態,我應該在通知欄上收到通知。 – user3513902

    相關問題