1,推送消息的发送
--- AppDelegate.swift ---
import UIKit @UIApplicationMain class AppDelegate : UIResponder , UIApplicationDelegate { var window: UIWindow ? func application(application: UIApplication dIDFinishLaunchingWithOptions launchOptions: [ NSObject : AnyObject ]?) -> Bool { //开启通知 let settings = UIUserNotificationSettings (forTypes: [. Alert Badge Sound ], categorIEs: nil ) application.registerUserNotificationSettings(settings) return true } applicationWillResignActive(application: ) { } applicationDIDEnterBackground(application: ) { } applicationWillEnterForeground(application: ) { } applicationDIDBecomeActive(application: ) { } applicationWillTerminate(application: ) { } } |
--- VIEwController.swift ---
VIEwController UIVIEwController { overrIDe vIEwDIDLoad() { super .vIEwDIDLoad() //发送通知消息 scheduleNotification(12345); //清除所有本地推送 //UIApplication.sharedApplication().cancelAlllocalnotifications() } //发送通知消息 scheduleNotification(itemID: Int ){ //如果已存在该通知消息,则先取消 cancelNotification(itemID) //创建UIlocalnotification来进行本地消息通知 localnotification = UIlocalnotification () //推送时间(设置为30秒以后) localnotification.fireDate = NSDate (timeIntervalSinceNow: 30) //时区 localnotification.timeZone = NSTimeZone .defaultTimeZone() //推送内容 localnotification.alertbody = "来自hangge.com的本地消息" //声音 localnotification.soundname = UIlocalnotificationDefaultSoundname //额外信息 localnotification.userInfo = [ "ItemID" :itemID] .sharedApplication().schedulelocalnotification(localnotification) } //取消通知消息 cancelNotification(itemID: ){ //通过itemID获取已有的消息推送,然后删除掉,以便重新判断 existingNotification = self .notificationForThisItem(itemID) as ? if existingNotification != { //如果existingNotification不为nil,就取消消息推送 .sharedApplication().cancellocalnotification(existingNotification!) } } //通过遍历所有消息推送,通过itemID的对比,返回UIlocalnotification notificationForThisItem(itemID: )-> ? { allNotifications = .sharedApplication().scheduledlocalnotifications for notification in allNotifications! { info = notification.userInfo as ! [ String ] number = info[ ] number != && number == itemID { return UIlocalnotification } } nil } dIDReceiveMemoryWarning() { .dIDReceiveMemoryWarning() } } |
2,点击推送消息的响应 收到推送,如果点击推送内容,则会重新进入到App,这个时候会调用AppDelegate中的func application(application: UIApplication,dIDReceivelocalnotification notification: UIlocalnotification)代理方法。 在这个方法中我们可以根据推送的消息内容实现相关的功能。
dIDReceivelocalnotification notification: ) { //设定Badge数目 .sharedApplication().applicationIconBadgeNumber = 0 ] ] alertController = UIAlertController (Title: "本地通知" "消息内容:\(notification.alertbody)用户数据:\(number)" UIAlertControllerStyle . )
alertController.addAction(cancel); .window?.rootVIEwController!.presentVIEwController(alertController, animated: true ) } |
以上是内存溢出为你收集整理的Swift - 本地消息的推送通知(附样例)全部内容,希望文章能够帮你解决Swift - 本地消息的推送通知(附样例)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)