美文网首页
[iOS笔记]本地推送的基本使用(iOS 10)

[iOS笔记]本地推送的基本使用(iOS 10)

作者: Seacen_Liu | 来源:发表于2018-04-30 17:49 被阅读0次

主要步骤

主要步骤

申请和注册

  • 使用UserNotifications.framework前我们需要导入它
import UserNotifications
  • 一般放在AppDelegate中的注册通知步骤
func registerNotification() {
        // 使用 UNUserNotificationCenter 来管理通知
        let center = UNUserNotificationCenter.current()
        // 监听回调事件
        center.delegate = self
        //iOS 10 使用以下方法注册,才能得到授权,注册通知以后,会自动注册 deviceToken,如果获取不到 deviceToken,Xcode8下要注意开启 Capability->Push Notification。
        center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
            if let err = error {
                print(err)
                return
            }
            if granted {
                print("通知注册成功")
            }
        }
    }

创建和发送

基本的创建

//需创建一个包含待通知内容的 UNMutableNotificationContent 对象,注意不是 UNNotificationContent ,此对象为不可变对象。
        let content = UNMutableNotificationContent()
        // 标题
        content.title = "标题"
        // 子标题
        content.subtitle = "子标题"
        // 内容
        content.body = "内容"
        // 标记个数
        content.badge = 1
        // 推送提示音
        content.sound = UNNotificationSound.default()
        
        // 指定音频文件
//        content.sound = UNNotificationSound(named: "prompt.mp3")
        
        // 附加信息
        content.userInfo = ["key1": "value1", "key2": "value2"]
        // 添加附件
        if let imageUrl = Bundle.main.url(forResource: "nico", withExtension: "png"),
            let attachment = try? UNNotificationAttachment(identifier: "imageAttachment", url: imageUrl, options: nil) {
            content.attachments = [attachment]
        } else {
            print("添加附件失败")
        }

发送三步走:

  1. 创建trigger
  2. 创建request
  3. 发送请求

trigger用于控制发送的时机

  • 延时发送
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)
  • 固定时间发送
let dateComponents = NSDateComponents()
dateComponents.year = 2018
dateComponents.month = 4
dateComponents.day = 30
dateComponents.hour = 16
dateComponents.minute = 48
dateComponents.second = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
  • 固定区域发送(在进入某个区域后推送本地推送,注意:此处用CLCircularRegion,不要用CLRegion)
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 21, longitude: 110), radius: 1000, identifier: "SeacenRegion")
let triggerRegion = UNLocationNotificationTrigger(region: region, repeats: false) 

创建请求和发送请求

let request = UNNotificationRequest(identifier: "Seacen", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
    if let err = error {
        print(err)
    } else {
        print("推送添加成功")
    }
}

展示和处理

本地推送在App活跃在前台时,是不会展示出来的
我们可以通过UNUserNotificationCenterDelegate这个代理来对通知做处理,在创建的时候我们也设置了UNUserNotificationCenter的代理,下面只需要实现failing方法

/// App在前台时收到推送会调用
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("在前台时通知 : \(notification)")
    }
    /// App不在前台时收到推送用户点开会调用
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("不在前台时收到通知时 : \(response)")
    }

这样我们就可以在AppDelegate中拿到推送,通过内容,我们可以做一系列的操作。


本文记录了iOS10之后UserNotifications中的本地通知功能的基本使用,进一步了解可到喵神的博客

相关文章

网友评论

      本文标题:[iOS笔记]本地推送的基本使用(iOS 10)

      本文链接:https://www.haomeiwen.com/subject/ynftrftx.html