iOS通知中心

iOS通知中心

它是iOS程序内部的一种消息广播机制,通过它,可以实现无引用关系的对象之间的通信。通知中心他是基于观察者模式,它只能进行程序内部通信,不能跨应用程序进程通信。

当通知中心接受到消息后会根据设置,将消息发送给订阅者,这里的订阅者可以有多个

通知中心原理

看完上图你应该明白通知中心所做的事情了吧, 接下来我们就来看看通知中心。

首先必须了解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)
    }

除了上面这种方式系统还有一个

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

但是在项目中并不多用, 所以就不详细介绍了,其实用法差不多, 只不过用的时候需要注意循环引用问题, 比如你在内部用self, 这个self对应的class对象就不会被释放

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

系统通知

除了自定义的通知名, 系统其实还有一部分通知名

UIDevice通知

UIDeviceOrientationDidChangeNotification    // 设备旋转 
UIDeviceBatteryStateDidChangeNotification   // 电池状态改变 
UIDeviceBatteryLevelDidChangeNotification   // 电池电量改变 
UIDeviceProximityStateDidChangeNotification // 近距离传感器(比如设备贴近了使用者的脸部)

键盘通知

UIKeyboardWillShowNotification // 键盘即将显示 
UIKeyboardDidShowNotification // 键盘显示完毕 
UIKeyboardWillHideNotification // 键盘即将隐藏 
UIKeyboardDidHideNotification // 键盘隐藏完毕 
UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变 
UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕

系统发出键盘通知时, 会附带一下跟键盘有关的额外信息(字典),字典常见的key如下:

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
原文地址:https://www.cnblogs.com/MrTao/p/5852525.html