Xcode 10 स्विफ्ट 4.2
पुश सूचना दिखाने के लिए जब आपका ऐप अग्रभूमि में हो -
चरण 1: AppDelegate वर्ग में प्रतिनिधि UNUserNotificationCenterDelegate जोड़ें।
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
चरण 2: UNUserNotificationCenter प्रतिनिधि सेट करें
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
चरण 3: यह चरण आपके ऐप को पुश सूचना को तब भी दिखाने की अनुमति देगा जब आपका ऐप अग्रभूमि में हो
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
चरण 4: यह चरण वैकल्पिक है । जांचें कि क्या आपका ऐप अग्रभूमि में है और यदि वह अग्रभूमि में है, तो लोकल पुशॉटिफिकेशन दिखाएं।
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
// go to screen relevant to Notification content
print("background")
} else {
// App is in UIApplicationStateActive (running in foreground)
print("foreground")
showLocalNotification()
}
}
स्थानीय अधिसूचना समारोह -
fileprivate func showLocalNotification() {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "App Update"
//content.subtitle = "local notification"
content.body = "New version of app update is available."
//content.badge = 1
content.sound = UNNotificationSound.default()
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
notificationCenter.add(request, withCompletionHandler: nil)
}