好东西小知识点IOS

iOS-消息推送

2017-05-14  本文已影响149人  FlyElephant

iOS 消息推送包括远程推送通知(Remote Notification)和本地推送通知(Local Notification),推送通知的形式从顶部显示,屏幕中间显示,锁屏通知,更新App未读消息数字.

远程通知

iOS 远程推送通知需要在App中开启推送通知选项,申请推送证书,实际推送过程如下图:

推送通知.png

App打开推送开关,用户要确认TA希望获得该App的推送消息.
① iPhone 与 苹果服务器建立长连接.
② APNS 远程推送推送服务返回deviceToken.
③ 客户端App 将DeviceToken 与 用户ID上传至服务端.
④ 服务端根据推送消息系统,将对应的消息,按照devicetoken发送至APNS.
⑤ APNS 将消息推送至客户端.

本地通知

本地消息一般比较少见,加入正在做一个To-do的工具类应用,对于用户加入的每一个事项,都会有一个完成的时间点,用户可以要求这个To-do应用在事项过期之前的某一个时间点提醒一下TA。为了达到这一目的,App就可以调度一个本地通知,在时间点到了之后发出一个Alert消息或者其他提示.

本地通知比较好模拟,iOS 10 中通知有所改变,AppDelegate中注册通知:
<pre><code>` func registerLocalNotification() {

    let center:UNUserNotificationCenter = UNUserNotificationCenter.current()
    center.delegate = self
    
    center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
        if granted {
            print("注册成功")
            center.getNotificationSettings(completionHandler: { (settings) in
                print("通知设置---\(settings)")
            })
        } else {
            print("注册失败")
        }
    }
    
}`</code></pre>

实现UNUserNotificationCenterDelegate:
<pre><code>` func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("didReceive 接受通知")
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("iOS10 通知")
    completionHandler( [.alert,.sound,.badge])
}

`</code></pre>

发送通知:
<pre><code>` let content:UNMutableNotificationContent = UNMutableNotificationContent()
content.body = "Body:你现在学习成绩不错,继续加油哦"
content.title = "Title:温馨提示"
content.subtitle = "Subtitle:FlyElephant"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = requestIdentifier

    if let path = Bundle.main.path(forResource: "test", ofType: "jpg") {
        let url = URL(fileURLWithPath: path)
        
        do {
            let attachment = try UNNotificationAttachment(identifier: "testImage", url: url, options: nil)
            content.attachments = [attachment]
        } catch {
            print("文件不存在.")
        }
    }
    
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
    let request = UNNotificationRequest(identifier: "FlyElephant-Trrigger", content: content, trigger: trigger) // 请求通知
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error : Error?) in
        if let theError = error {
            print("通知--\(theError)")
        }
        print("通知成功")
    }`</code></pre>

取消通知:
<pre><code>let center = UNUserNotificationCenter.current() center.removePendingNotificationRequests(withIdentifiers: [requestIdentifier])</code></pre>

测试效果:


FlyElephant.png
上一篇下一篇

猜你喜欢

热点阅读