本地推送(UILocalNotification)和远程推送其目的都是要提醒用户去做某件事情,其本质区别有两点:(1)是否需要联网?(2)触发者是谁?简单来说,本地推送是由用户(App使用者)触发,不需要联网,类似的比如ToDoList,一对一推送;而远程推送触发者是App运营者,为了宣传产品提高用户粘合度,推送形式单对多,需要联网。
Step1:iOS8之后推送要求必须注册App支持的用户交互类型,注册代码和远程推送注册代码相同如下
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge,UIUserNotificationType.Alert,UIUserNotificationType.Sound]categories: [category]))
如果没有特殊需求(比如使用到UIMutableUserNotificationAction)可以将后面的categories设置为nil
在介绍下一步之前有必要说一下UILocalNotification的基本属性便于大家理解使用
属性名 | 类型 | 备注 | 英文原版 |
---|---|---|---|
fireDate | NSDate? | 代表推送的启动时间 | timer-based scheduling |
timeZone | NSTimeZone? | 说明设置的fireDate在哪个时区 | the time zone to interpret fireDate in |
repeatInterval | NSCalendarUnit | 重复次数 | nil |
repeatCalendar | NSCalendar? | 重复推送时间 | nil |
alertBody | String? | 通知内容 | pass a string or localized string key to show an alert |
alertAction | String? | 解锁滑动时的事件 | used in UIAlert button or 'slide to unlock...' slider in place of unlock |
soundName | String | 消息推送提示声音 | name of resource in app's bundle to play or UILocalNotificationDefaultSoundName |
alertLaunchImage | String? | 启动图片,设置此字段点击通知时会显示该图片 | used as the launch image (UILaunchImageFile) when launch button is |
alertTitle | String? | 消息标题,默认无 | defaults to nil. pass a string or localized string key |
applicationIconBadgeNumber | Int | App icon的角标 | 0 means no change. defaults to 0 |
userInfo | [NSObject : AnyObject]? | 自定义参数 | nil |
Step2:添加推送通知
@IBAction func sendLocalNotification(sender: UIButton) {
let localNotification = UILocalNotification();
//触发通知时间
localNotification.fireDate = NSDate(timeIntervalSinceNow:5);
//重复间隔
// localNotification.repeatInterval = kCFCalendarUnitMinute;
localNotification.timeZone = NSTimeZone.defaultTimeZone();
//通知内容
localNotification.alertBody = "本地消息推送测试";
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
//通知参数
localNotification.userInfo = ["message": "本地消息"];
localNotification.category = "categoryIdentifier";
UIApplication.sharedApplication().scheduleLocalNotification(localNotification);
}
至此,本地推送已经完成,但需要说明的是,如果推送发生时,App处于Foreground会直接调用
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
如果App处于Background状态时,此时触发推送会在通知栏产生一条消息,当你点击推送消息后才会触发上面的方法。
如果你想实现特殊的消息推送,比如快速点赞、回复等,可使用UIMutableUserNotificationAction定义不同的action并指定其唯一的identifier,因为无需打开App可直接将action的activationMode设置为Background,处理函数为:
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, withResponseInfo responseInfo: [NSObject : AnyObject], completionHandler: () -> Void){
if identifier == "yourIdentifier"{
//do something..
}else{
//else do...
}
completionHandler()
}
网友评论