Тестовая среда:
До теста:
Изготовитьубедитесь, что профили обеспечения созданы и установлены правильно.
Включить Фоновые режимы (включая Удаленные уведомления ) и Push-уведомления в проекте
Шаги теста:
Подключите кабель к мобильному компьютеру от Mac, и пусть приложение находится в режиме background ,
Отправка APN через Easy APNs Provider * Инструмент 1038 *, установите content-available
в 1
// This is payload content:
{
"aps" : {
"alert" : "hello",
"sound" : "default",
"content-available" : 1
}
}
Устройство получило уведомление, сначала всплыло уведомление "привет" с сервера APN и неявно активировало приложение, затем всплыло уведомление "Внутри" из приложения.
Поведение является нормальным, когда мобильное устройство подключено к Mac, но когда я отключаю мобильное устройство от Mac, на нем больше не может появиться уведомление «Inside».
Это простой тестовый код для тихого удаленного push-уведомления:
//
// ViewController.swift
//
import UIKit
import Foundation
import UserNotifications
class ViewController: UIViewController, UIPickerViewDelegate {
@IBAction func createNotification(_ sender: AnyObject) {
let content = UNMutableNotificationContent()
content.title = "TITLE"
content.subtitle = "SUBTITLE"
content.body = "Inside"
content.badge = 1
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: "notification1", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// When launching the app into foreground mode, pop up notification every two seconds
let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(showMsg), userInfo: nil, repeats: true)
}
@objc func showMsg() {
createNotification(UIButton())
}
}
//
// AppDelegate.swift
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge], completionHandler: { (granted, error) in
if granted { print("granted") }
else { print("denied") }
})
// register remote push notification
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("deviceTokenString: \(deviceTokenString)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("error: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//completionHandler(.newData)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// Show push notifications in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}