以前曾经写过iOS的远程推送那时候是用OC语言实现的,现在简单的介绍一下iOS的本地推送
相比远程推送本地推送省略了麻烦的证书问题所以很简单。
一样的我们在程序的开始都需要注册推送:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//注册本地推送
if #available(iOS 8.0, *) {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil))
} else {
}
return true
注册好了之后我们尝试着发送推送:
//发送本地推送消息
func sendLocalNotiction() {
//创建推送UILocalNotification
let localNotifiction = UILocalNotification()
//推送时间30s后
localNotifiction.fireDate = NSDate(timeIntervalSinceNow: 30)
//时区(本地)
localNotifiction.timeZone = NSTimeZone.systemTimeZone()
//推送消息
localNotifiction.alertBody = "本地推送消息\(NSDate())"
//角标设置
localNotifiction.applicationIconBadgeNumber = 1
if #available(iOS 8.2, *) {
localNotifiction.alertTitle = "本地推送测试"
} else {
// Fallback on earlier versions
}
//推送声音系统声音,也可以是bundle里面的音乐
localNotifiction.soundName = UILocalNotificationDefaultSoundName
//附加信息
localNotifiction.userInfo = ["name":"句芒"]
//添加推送
UIApplication.sharedApplication().scheduleLocalNotification(localNotifiction)
//取消推送
//UIApplication.sharedApplication().cancelLocalNotification(localNotifiction)
}
当然了能够发推送肯定也可以取消推送的,
UIApplication.sharedApplication().cancelLocalNotification(localNotifiction)
这样就可以取消推送了。
接到推送后我们一般会点击app进入前台处理推送的:
//接收本地消息了
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
//角标清零
application.applicationIconBadgeNumber = 0
let info = notification.userInfo as! [String:String]
let name = info["name"]
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: "推送", message: "收到了推送内容用户名:\(name!)", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "知道了", style: .Cancel, handler: { (alert) in
}))
self.window?.rootViewController!.presentViewController(alertController, animated: true, completion: nil)
} else {
// Fallback on earlier versions
let alert = UIAlertView(title: "推送", message: "收到了推送内容用户名:\(name!)", delegate: nil, cancelButtonTitle: "知道了")
alert.show()
}
}