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,然後如圖