(初学者有写的不对的希望大家指导)
注册通知 iOS 10及以上用户适用
业务场景: app内用户做任务经常会忘记签出,这边做个到时间就提示签出。
first :请求权限
(1)iOS 10 统一了推送权限的申请:
/// 注册
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]){accepted, error in
if !accepted{
print("Notification access denied.")
}else{
print("Notification access allowed.")
}
}
这一步写出来就知道有点不合适了吧,需要用户同意你的推送权限。万一用户点了个拒绝咋办啊,真心头疼。我拿真心照明月,奈何明月照沟渠。跑题了。不过这个还是运营来解决吧。
Second:注册回调(这步很重要,我当时就是没有写这个导致我的通知怎么都发不出去。)
extension ViewController : UNUserNotificationCenterDelegate{
//发送成功执行的方法,
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
}
//点击通知执行的方法
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//判断用户在何种状态下进行的操作
let status = UIApplication.shared.applicationState
switch status {
case .active://前台
print("前台")
break
case .inactive://从后台进前台
print("从后台进前台")
break
case .background://后台
print("后台")
break
default:
print("default")
break
}
}
}
里面怎么处理还是要看自己的业务啊Third:这步就是确定你的发送方式了
我们可以有几种发送方式:比如我想定时发送 我想延时发送 按日期来发送 范围发送(定位) 这些需求我们接下来看看怎么实现
1:定时发送 每天 11点10分10秒 准时发送’
let content = UNMutableNotificationContent()
content.title = "你知道本地通知么?"//标题
content.subtitle = "你不会是个傻子吧"//副标题
content.body = "嗷呦"//内容
content.badge = 10 //通知个数
//定时,每日 11点11分11秒 推送消息(分/秒不给的话就是11点发送)
var compoent : DateComponents = DateComponents.init()
//compoent.weekday=4//周三(你懂得外国的日期)
compoent.hour=11
compoent.minute=11
compoent.second=11
let tigger = UNCalendarNotificationTrigger.init(dateMatching: compoent, repeats: true)
//不同的标识生成不同的弹出框(identifier)这是个标识
let request = UNNotificationRequest.init(identifier: "哈哈哈哈哈", content: content, trigger: tigger)
UNUserNotificationCenter.current().add(request) { erro in
}
2:延时发送
//设置5秒后触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
3:设置日期
/// 触发机制
func scheduleNotification(at date: Date) {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
.......
}
4:设置范围
//100米范围内,进入触发。
let Coordinate2:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 39, longitude: 116);
let region:CLCircularRegion = CLCircularRegion(center: Coordinate2, radius: 100, identifier: "center")
region.notifyOnEntry = true;
region.notifyOnExit = false;
let triggerRegion = UNLocationNotificationTrigger(region: region, repeats: true);
以上就是这次通知所做的总结。如有不清楚的或者需要讨论的可以给我发邮件 henry.geng@aliyun.com