一、苹果推送原理
从上图我们可以看到:
1、应用程序注册消息推送。
2、iOS从APNs获取device Token,应用程序接收device Token。
3、应用程序将device token发送给PUSH服务端程序。
4、服务端程序向APNS服务发送消息。
5、APNS服务将消息发送给iPhone应用程序。
二、本地推送步骤
- 先注册一个本地通知:
public func setNotifiAuth() {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted == true {
print("允许通知")
} else {
print("不允许通知")
}
}
}
- 添加一个本地通知
public func send(_ body: String) {
let content = UNMutableNotificationContent()
content.title = "本地推送消息"
content.subtitle = "******"
content.body = body
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.1, repeats: false)
let request = UNNotificationRequest.init(identifier: "req_identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
- 移除通知
// 移除一个通知
public func removeOneNotification(_ noticeId: String) {
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { requests in
requests.forEach { req in
print("存在的ID:\(req.identifier)\n")
}
}
print("移除currentID:\(noticeId)")
center.removePendingNotificationRequests(withIdentifiers: [noticeId])
}
// 移除所有通知
public func removeAllNotification() {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications()
}
三、 远程推送
- 服务端生成APNS pem证书
- 开启Xcode远程推送功能
- 注册设备ID