6
如何設置我的AppDelegate處理推時,應用程序是在前臺,並在迅速3個iOS 10後臺發生的通知?包括如果我收到通知時如何使手機在前臺振動。如何處理IOS推送通知時,應用程序是在前臺?
如何設置我的AppDelegate處理推時,應用程序是在前臺,並在迅速3個iOS 10後臺發生的通知?包括如果我收到通知時如何使手機在前臺振動。如何處理IOS推送通知時,應用程序是在前臺?
這是我如何設置我的AppDelegate文件來做到這一點:
要處理推送通知,導入以下框架:
import UserNotifications
爲了使在任何設備進口下列框架手機震動:
import AudioToolbox
讓你的AppDelegate一個UNUserNotificationCenterDelegate:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
在你的「didFinishLaunchingWithOptions」補充一點:
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted) {
UIApplication.shared.registerForRemoteNotifications()
} else{
print("Notification permissions not granted")
}
})
這將確定用戶是否此前曾表示,您的應用程序可以發送通知。如果沒有,處理它,你怎麼樣。
要訪問該設備令牌一旦註冊:
//Completed registering for notifications. Store the device token to be saved later
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
self.deviceTokenString = deviceToken.hexString
}
比特產是一個擴展我添加到我的項目:
extension Data {
var hexString: String {
return map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
}
}
爲了處理時會發生什麼你的應用程序收到通知在前景:
//Called when a notification is delivered to a foreground app.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//Handle the notification
//This will get the text sent in your notification
let body = notification.request.content.body
//This works for iphone 7 and above using haptic feedback
let feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator.notificationOccurred(.success)
//This works for all devices. Choose one or the other.
AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
}
要處理您的應用收到
//Called when a notification is delivered to a background app.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) {
//Handle the notification
print("did receive")
let body = response.notification.request.content.body
completionHandler()
}
:在後臺中,用戶然後按下上的通知的通知