NSNotificationCenter

NSNotificationCenter是专门供程序中不同类间的消息通信的。使用它为我们代码降低耦合。

自定义数据监听

  • 注册监听:

// addObserver 4个参数分别是:接受者对象,接受者处理函数,消息名称,发送者对象(通常设为nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(downloadImage), name: "NotificationName", object: nil)
  • 移除监听:

NSNotificationCenter.defaultCenter().removeObserver(self)
  • 监听函数:

func downloadImage(notification: NSNotification) {let userInfo = notification.userInfo as! [String: AnyObject]let value1 = userInfo["val1"] as! Stringlet value2 = userInfo["val2"] as! Int// ...
}
  • 发送消息:

NSNotificationCenter.defaultCenter().postNotificationName("NotificationName",object: self, userInfo: ["val1":"msg1", "val2" : 123])

默认监听

  • addObserverForName监听方法

let operationQueue = NSOperationQueue.mainQueue()
// queue必须是处理队列NSOperationQueue,usingBlock是响应消息的函数闭包
NSNotificationCenter.defaultCenter().addObserverForName("NotificationName2", object: nil, queue: operationQueue, usingBlock: { /*...*/ })
  • postNotificationName

系统会发送很多消息,如:

UIApplicationDidEnterBackgroundNotification
UIApplicationWillEnterForegroundNotification
UIApplicationDidFinishLaunchingNotification
...

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onKeyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onKeyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onEnterBackground), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(onEnterForeground), name: UIApplicationDidBecomeActiveNotification, object: nil)

发送不带数据的消息:

NSNotificationCenter.defaultCenter().postNotificationName("NotificationName2", object: self)

发送本地通知栏通知

  • 注册用户消息设置

可以设置在AppDelegate的didFinishLaunchingWithOptions内部

let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
application.registerUserNotificationSettings(settings)

这样,安装后首次进入应用系统会提示是否允许接收通知。

  • 发送消息

获取一个UILocalNotification
发送:UIApplication.sharedApplication().presentLocalNotificationNow(notification)

let notification = UILocalNotification()
notification.fireDate = NSDate().dateByAddingTimeInterval(3) // 延迟3秒发送消息
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.Minute // 设置每分钟重复一次
notification.alertTitle = "This is a notification title"
notification.alertBody = "This is a notification body"
notification.alertAction = "OK"
notification.soundName = UILocalNotificationDefaultSoundName  // 默认提示音
notification.applicationIconBadgeNumber = 1  // 应用Icon的悬浮数字
// 使用userInfo数据
var userInfo:[NSObject : AnyObject] = [NSObject : AnyObject]()
userInfo["kLocalNotificationID"] = "LocalNotificationID"
userInfo["key"] = "Attention Please"
notification.userInfo = userInfoUIApplication.sharedApplication().scheduleLocalNotification(notification)
// 如果不延时就现在发送
// UIApplication.sharedApplication().presentLocalNotificationNow(notification)
  • 处理消息

当我们在系统通知栏里点击到我们的通知,跳转到应用时,系统会触发
application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
我们就在下面写我们的处理逻辑

print("didReceiveLocalNotification \(notification.alertTitle)")let userInfo = notification.userInfo!
let title = userInfo["key"] as! Stringlet alert = UIAlertController(title: title, message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
alert.title = title
alert.message = notification.alertBody
let okAction = UIAlertAction(title: "OK!!!", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okAction)
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
  • 清除Icon的通知数字

我们在应用激活状态,就去清除掉数字
应用别激活就会调用:
applicationDidBecomeActive(application: UIApplication)

application.cancelAllLocalNotifications()
application.applicationIconBadgeNumber = 0

IOS-Swift开发基础——通知相关推荐

  1. IOS UI开发基础之超级猜图完整版本-08

    IOS UI开发基础之超级猜图完整版本-08 // // ViewController.m // 09-超级猜图 // // Created by 鲁军 on 2021/1/31. //#import ...

  2. IOS swift开发——获取设备定位信息

    作为GIS开发人员,学习任何Android或者swift开发语言,可能第一时间想到的就是获取设备的定位信息.这里就来简述一下,我使用swift获取IOS定位信息的过程. 目录 添加后台定位能力 模拟器 ...

  3. iOS swift UITest 基础入门(一)

    在项目组内做UITest几个月了,输出才是真正的提高嘛,总结了一下,写出来做一个UITest的讲解. 首先说一下目的:UITest,可以模拟人的操作,当然还可以使用第三方用以模拟网络请求,再加上数据库 ...

  4. ios直播开发基础,推流协议及流程

    一:推流需要的三方库和一些常用格式和协议介绍 1.rtmp协议 :实时消息传输协议,Adobe Systems公司为Flash播放器和服务器之间音频.视频和数据传输开发的开 放协议,因为是开放协议所以 ...

  5. Objective-C ,ios,iphone开发基础:UIAlertView使用详解

    UIAlertView使用详解 Ios中为我们提供了一个用来弹出提示框的类 UIAlertView,他类似于javascript中的alert 和c#中的MessageBox(); UIAlertVi ...

  6. [置顶] Objective-C ,ios,iphone开发基础:命名规范

    命名规范:http://bukkake.iteye.com/blog/695492  点击打开链接 转载于:https://www.cnblogs.com/pangblog/p/3292256.htm ...

  7. Objective-C ,ios,iphone开发基础:NSDictionary(字典) 和 NSMutableDictionary

    NSDictionary(字典),NSDictionary类似于 .net中的parameter,l类似于java中的map. 通过唯一的key找到对应的值,一个key只能对应一个只,而多个key可以 ...

  8. [置顶] Objective-C,/,ios,/iphone开发基础:分类(category,又称类别)

    在c++中我们可以多继承来实现代码复用和封装使程序更加简练.在objective-c中只能单继承,不能多继承,那么除了协议protocol之外,我们可以实现类似多继承的一个方法就是,分类(catego ...

  9. iOS 应用开发基础翻译 改为 笔记和总结

    实在是翻译能力不高,翻译出来的中国话怎么读都别扭,所以此系列改为阅读笔记和总结,FYI. 转载于:https://www.cnblogs.com/csusheep/p/4459623.html

最新文章

  1. Nature子刊评论:2020年后,微生物组将如何发展?
  2. pandas读取csv文件的前几行数据(nrows参数)、pandas读取csv文件的中间几行数据(skiprows=range(a,b))
  3. 怎么会执行sql 懒加载 没用_太神奇的 SQL 查询经历,group by 慢查询优化!
  4. 51 MM配置-库存管理和实际库存-设置“交货完成”标识
  5. ubuntu vim中输入中文
  6. Spring中都用到了哪些设计模式
  7. 汉诺塔c语言代码实现
  8. idea 编程字体推荐
  9. java基于spingboot+vue的拼团旅游系统 elementui
  10. Travis Ci 让你的项目轻松加入持续集成测试
  11. 蓝牙耳机买什么品牌好一些?2022蓝牙耳机品牌排行榜10强
  12. wps参考文献乱码。英文的行间距怎么调?
  13. RadioGroup 全部取消选中 和选中某个按钮
  14. 火狐插件restclient发送post请求
  15. VS2019下编译x264.dll
  16. 程序员干到30岁,真的只能转行了么?
  17. 树莓派桌面多出个计算机,树莓派|计算机实验室之树莓派:课程 9 屏幕04
  18. 太敢拍了!20万条弹幕告诉你,《扫黑风暴》为何能掀起收视热潮?
  19. 一些常见warning的原因和解决方法
  20. 双线性插值算法推导及代码实现

热门文章

  1. 为清理助手制作便利工具的技术实现
  2. 关于IIS正在使用突然断电后,IIS不能使用解决方案
  3. 房地产CRM系列之三:客户营销
  4. 【干货】史上最全的Tensorflow学习资源汇总,速藏!
  5. angular核心原理解析3:指令的执行过程
  6. android常见错误-Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
  7. 上海技术英雄会续:几个典型问题的看法
  8. .net开发框架比较
  9. nagios全攻略(三)----使用插件监控更多信息
  10. 用Windows系统实现RAID功能