iOS通知中心

iOS通知中心

它是iOS程序內部的一種消息廣播機制,經過它,能夠實現無引用關係的對象之間的通訊。通知中心他是基於觀察者模式,它只能進行程序內部通訊,不能跨應用程序進程通訊。app

當通知中心接受到消息後會根據設置,將消息發送給訂閱者,這裏的訂閱者能夠有多個ide

通知中心原理

看完上圖你應該明白通知中心所作的事情了吧, 接下來咱們就來看看通知中心。post

首先必須瞭解2個類: 動畫

// 這個類用來傳遞發送通知過程當中傳遞信息的載體
NSNotification
// 這是iOS中通知中心的靈魂, 由該類實現了觀察者模式, 並給開發者提供了諸如註冊、刪除觀察者的接口, 咱們能夠經過一個單例來得到它的實例
NSNotificationCenter

代碼實現

註冊一個通知觀察者

// 註冊一個通知觀察者
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.refreshText(_:)), name: kRefreshTextNotification, object: nil)
self: 觀察者
selector: 收到通知執行的方法
name: 通知名
object: 

// 收到通知後執行的方法
func refreshText(notification: NSNotification) {
        if notification.object is NSError {
            return
        }
        
        textField.text = String(notification.object!)
}

向觀察者發送通知

NSNotificationCenter.defaultCenter().postNotificationName(kRefreshTextNotification, object: "fffffff", userInfo: nil)
kRefreshTextNotification: 通知名
object: 參數
userInfo: 其餘參數

移除觀察者

deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: kRefreshTextNotification, object: nil)
    }

除了上面這種方式系統還有一個ui

NSNotificationCenter.defaultCenter().addObserverForName(kRefreshTextNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) in}

可是在項目中並很少用, 因此就不詳細介紹了,其實用法差很少, 只不過用的時候須要注意循環引用問題, 好比你在內部用self, 這個self對應的class對象就不會被釋放spa

移除觀察者須要注意 不能用 NSNotificationCenter.defaultCenter().removeObserver(self, name: kRefreshTextNotification, object: nil), 須要用 NSNotificationCenter.defaultCenter().removeObserver(observer)rest

系統通知

除了自定義的通知名, 系統其實還有一部分通知名code

UIDevice通知

UIDeviceOrientationDidChangeNotification    // 設備旋轉 
UIDeviceBatteryStateDidChangeNotification   // 電池狀態改變 
UIDeviceBatteryLevelDidChangeNotification   // 電池電量改變 
UIDeviceProximityStateDidChangeNotification // 近距離傳感器(好比設備貼近了使用者的臉部)

鍵盤通知

UIKeyboardWillShowNotification // 鍵盤即將顯示 
UIKeyboardDidShowNotification // 鍵盤顯示完畢 
UIKeyboardWillHideNotification // 鍵盤即將隱藏 
UIKeyboardDidHideNotification // 鍵盤隱藏完畢 
UIKeyboardWillChangeFrameNotification // 鍵盤的位置尺寸即將發生改變 
UIKeyboardDidChangeFrameNotification // 鍵盤的位置尺寸改變完畢

系統發出鍵盤通知時, 會附帶一下跟鍵盤有關的額外信息(字典),字典常見的key以下:server

UIKeyboardFrameBeginUserInfoKey // 鍵盤剛開始的frame 
UIKeyboardFrameEndUserInfoKey // 鍵盤最終的frame(動畫執行完畢後) 
UIKeyboardAnimationDurationUserInfoKey // 鍵盤動畫的時間 
UIKeyboardAnimationCurveUserInfoKey // 鍵盤動畫的執行節奏(快慢)

app通知

// These notifications are sent out after the equivalent delegate message is called
@available(iOS 4.0, *)
public let UIApplicationDidEnterBackgroundNotification: String
@available(iOS 4.0, *)
public let UIApplicationWillEnterForegroundNotification: String
public let UIApplicationDidFinishLaunchingNotification: String
public let UIApplicationDidBecomeActiveNotification: String
public let UIApplicationWillResignActiveNotification: String
public let UIApplicationDidReceiveMemoryWarningNotification: String
public let UIApplicationWillTerminateNotification: String
public let UIApplicationSignificantTimeChangeNotification: String
public let UIApplicationWillChangeStatusBarOrientationNotification: String // userInfo contains NSNumber with new orientation
public let UIApplicationDidChangeStatusBarOrientationNotification: String // userInfo contains NSNumber with old orientation
public let UIApplicationStatusBarOrientationUserInfoKey: String // userInfo dictionary key for status bar orientation
public let UIApplicationWillChangeStatusBarFrameNotification: String // userInfo contains NSValue with new frame
public let UIApplicationDidChangeStatusBarFrameNotification: String // userInfo contains NSValue with old frame
public let UIApplicationStatusBarFrameUserInfoKey: String // userInfo dictionary key for status bar frame
@available(iOS 7.0, *)
public let UIApplicationBackgroundRefreshStatusDidChangeNotification: String
@available(iOS 3.0, *)
public let UIApplicationLaunchOptionsURLKey: String // userInfo contains NSURL with launch URL
@available(iOS 3.0, *)
public let UIApplicationLaunchOptionsSourceApplicationKey: String // userInfo contains NSString with launch app bundle ID
@available(iOS 3.0, *)
public let UIApplicationLaunchOptionsRemoteNotificationKey: String // userInfo contains NSDictionary with payload
@available(iOS 4.0, *)
public let UIApplicationLaunchOptionsLocalNotificationKey: String // userInfo contains a UILocalNotification
@available(iOS 3.2, *)
public let UIApplicationLaunchOptionsAnnotationKey: String // userInfo contains object with annotation property list
@available(iOS 4.0, *)
public let UIApplicationProtectedDataWillBecomeUnavailable: String
@available(iOS 4.0, *)
public let UIApplicationProtectedDataDidBecomeAvailable: String
@available(iOS 4.0, *)
public let UIApplicationLaunchOptionsLocationKey: String // app was launched in response to a CoreLocation event.
@available(iOS 5.0, *)
public let UIApplicationLaunchOptionsNewsstandDownloadsKey: String // userInfo contains an NSArray of NKAssetDownload identifiers
@available(iOS 7.0, *)
public let UIApplicationLaunchOptionsBluetoothCentralsKey: String // userInfo contains an NSArray of CBCentralManager restore identifiers
@available(iOS 7.0, *)
public let UIApplicationLaunchOptionsBluetoothPeripheralsKey: String // userInfo contains an NSArray of CBPeripheralManager restore identifiers
@available(iOS 9.0, *)
public let UIApplicationLaunchOptionsShortcutItemKey: String // userInfo contains the UIApplicationShortcutItem used to launch the app.

// Key in options dict passed to application:[will | did]FinishLaunchingWithOptions and info for UIApplicationDidFinishLaunchingNotification
@available(iOS 8.0, *)
public let UIApplicationLaunchOptionsUserActivityDictionaryKey: String // Sub-Dictionary present in launch options when user activity is present
@available(iOS 8.0, *)
public let UIApplicationLaunchOptionsUserActivityTypeKey: String // Key in user activity dictionary for the activity type

@available(iOS 8.0, *)
public let UIApplicationOpenSettingsURLString: String

// Keys for application:openURL:options:
@available(iOS 9.0, *)
public let UIApplicationOpenURLOptionsSourceApplicationKey: String // value is an NSString containing the bundle ID of the originating application
@available(iOS 9.0, *)
public let UIApplicationOpenURLOptionsAnnotationKey: String // value is a property-list typed object corresponding to what the originating application passed in UIDocumentInteractionController's annotation property
@available(iOS 9.0, *)
public let UIApplicationOpenURLOptionsOpenInPlaceKey: String // value is a bool NSNumber, set to YES if the file needs to be copied before use

// Content size category constants
@available(iOS 7.0, *)
public let UIContentSizeCategoryExtraSmall: String
@available(iOS 7.0, *)
public let UIContentSizeCategorySmall: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryMedium: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryExtraLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryExtraExtraLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryExtraExtraExtraLarge: String

// Accessibility sizes
@available(iOS 7.0, *)
public let UIContentSizeCategoryAccessibilityMedium: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryAccessibilityLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryAccessibilityExtraLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryAccessibilityExtraExtraLarge: String
@available(iOS 7.0, *)
public let UIContentSizeCategoryAccessibilityExtraExtraExtraLarge: String

// Notification is emitted when the user has changed the preferredContentSizeCategory for the system
@available(iOS 7.0, *)
public let UIContentSizeCategoryDidChangeNotification: String // userInfo dictionary will contain new value for UIContentSizeCategoryNewValueKey
@available(iOS 7.0, *)
public let UIContentSizeCategoryNewValueKey: String // NSString instance with new content size category in userInfo

// This notification is posted after the user takes a screenshot (for example by pressing both the home and lock screen buttons)
@available(iOS 7.0, *)
public let UIApplicationUserDidTakeScreenshotNotification: String

// Extension point identifier constants
@available(iOS 8.0, *)
public let UIApplicationKeyboardExtensionPointIdentifier: String
相關文章
相關標籤/搜索