1.本地推送
//设置通知触发器
let content=UNMutableNotificationContent()
content.title="hzk"
content.subtitle="阿哈!"//二级标题
content.body="有苍蝇!"
content.badge=NSNumber(value: badge) //角标
content.sound = UNNotificationSound.default //声音
//设置通知触发器:5s后触发推送
let trigger=UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
// //设置通知触发器:指定日期触发推送
// var components=DateComponents()
// components.year=2020
// components.month=11
// components.day=11
// let trigger2=UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
//
// //设置通知触发器:每周一上午8点半触发推送
// var components2=DateComponents()
// components2.weekday=2 //周一
// components2.hour=8 //上午8点
// components2.second=30 //30分
// let trigger3=UNCalendarNotificationTrigger(dateMatching: components2, repeats: true)
//
// //设置通知触发器:进入某地、离开某地触发推送
// let coordinate = CLLocationCoordinate2D(latitude:52.10,longitude:51.11)
// let region = CLCircularRegion(center: coordinate, radius: 200, identifier: "center")
// region.notifyOnEntry = true //进入此范围触发
// region.notifyOnExit = false //离开此范围不触发
// let trigger4 = UNLocationNotificationTrigger(region: region, repeats: true)
//设置请求标识符
let requestIdentifier="com.hzk.Mytest3Notification"
//设置一个通知请求
let request=UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Failed to add request to notification center. error:\(error)")
}
}
2.远程推送
原理:
步骤:
1.创建APPID:
首先我们需要登录到苹果的开发者官网https://developer.apple.com
选择Account进行登录(请确保自己已经加入到公司的program,这样才能有证书的显示页面)
点击Certificates,Identifiers & profiles然后选择identifiers下的AppIDS(APPID是应用的唯一标识)
,所以创建一个应用就需要一个APPID,点击途中蓝色的+号,选择AppID->APP,其中APPIDPrefix是APPID的前缀,每个账户有唯一的前缀,BundleID是APPID的后缀,有指定APPID和通配符APPID两种,我们需要用到Push Notifications功能所以得选择指定APPID,然后把Capabilities下面的Push Notifications勾住,然后选择continue,然后检查一下配置的信息后选择register
2.创建证书
选择Certificates谈后选择蓝色+号进行添加
证书包括俩种类型:开发证书和生产证书,我们选择在开发环境下进行消息推送的一项如图
然后选择我们刚才创建的APPID
上传证书请求文件
在电脑的 启动台->其他 中找到钥匙串
按如图所示打开
然后填写相关的信息,然后继续,储存到自己想保存的位置,我这里放到了文稿中
然后回到之前的页面点击Choose选择刚才创建好的文件选取即可
然后Download
等待下载完成后点击一下下载的文件就可以在钥匙串访问的证书栏看到一条新的证书
为生产环境生成一个推送证书,之后的步骤和测试环境下的推送证书一致,不再赘述
最后得到:
3.导出p12文件(p12文件包含证书和私钥信息)
右键导出
设置密码:密码要记住之后要用到,点击好之后输入本机密码即可
4.授权文件(用于真机测试)
选择IOS APP 开发
然后选择对应的APPID,然后如图