需要发送的地方
@IBAction func send() {
let content = UNMutableNotificationContent()
content.title = "title:測試本地通知"
content.subtitle = "subtitle:法蘭克"
content.body = "body:法蘭克的 iOS 世界"
content.badge = 1
content.sound = UNNotificationSound.default()
// let iconName = "compose_emoticonbutton_background"
// guard let iconUrl = Bundle.main.url(forResource: iconName, withExtension: "png") else {
// return
// }
//
// //2.通知的图片
// let attachment = try! UNNotificationAttachment(identifier: iconName, url: iconUrl, options: .none)
// content.attachments = [attachment]
//3
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
//4.
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
AppDelegate.swift
//MARK:- 无论是远程还是本地 APPDelegate都是这么写
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().tintColor = UIColor.orange
UITabBar.appearance().tintColor = UIColor.orange
//创建Window()
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = defaultVC
window?.makeKeyAndVisible()
//***************推送
//请求通知授权:本地、远程公用
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge,.carPlay]) { (success, error) in
if success {
print("允許")
} else {
print("不允許")
}
}
//注册远程通知
UIApplication.shared.registerForRemoteNotifications()
//设置代理:這麼做可讓 App 在前景狀態下收到通知
UNUserNotificationCenter.current().delegate = self
return true
}
//MARK:- appdelegate遵守协议
extension AppDelegate: UNUserNotificationCenterDelegate {
// 用于前台运行 :在前景收到通知時所觸發的 function
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("在前景收到通知...")
let userInfo = notification.request.content.userInfo
showLabel.backgroundColor = UIColor.red
showLabel.frame = CGRect(x: 0, y: 250, width: UIScreen.main.bounds.width, height: 300)
showLabel.text = userInfo.description
completionHandler([.badge, .sound, .alert])
}
//用于后台及程序退出
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("后台...")
}
//用于静默推送
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("接受远程")
}
//获取Token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("获取Token")
// 6184613f 8119ba47 5fde55c8 5f00769c 2a0aeba5 a971b38d 9453002c 1146013d
let device = NSData(data: deviceToken)
print("我的deviceToken\(device)")
}
}
网友评论