اعلان های پوش (Push Notifications)
اعلان پوش (Push Notification) پیام سیستمی است. این پیام از سرور می آید. سپس روی گوشی نمایش می شود. اول اجازه بگیر. بعد ثبت نام در APNs انجام بده. مثل کارت دانش آموزی که بدونش وارد مدرسه نمی شوی.
درخواست اجازه اعلان پوش
برای اجازه از UNUserNotificationCenter کمک بگیر. سپس وضعیت را بخوان. در صورت نیاز دوباره تنظیم کن.
import SwiftUI
import UserNotifications
struct PushPermissionDemo: View {
@State private var status: UNAuthorizationStatus? = nil
var body: some View {
VStack(spacing: 12) {
Text("Status: \(statusLabel)")
Button("Request Permission") {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
UNUserNotificationCenter.current().getNotificationSettings { s in
DispatchQueue.main.async {
status = s.authorizationStatus
}
}
}
}
}
.padding()
.onAppear {
UNUserNotificationCenter.current().getNotificationSettings { s in
DispatchQueue.main.async {
status = s.authorizationStatus
}
}
}
}
private var statusLabel: String {
switch status {
case .authorized?:
return "authorized"
case .denied?:
return "denied"
case .notDetermined?:
return "notDetermined"
case .provisional?:
return "provisional"
case .ephemeral?:
return "ephemeral"
default:
return "unknown"
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
PushPermissionDemo()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
نمایش اعلان در فورگراند
هنگام باز بودن برنامه، رفتار نمایش را کنترل کن. سپس آخرین پیام را شبیه سازی کن.
import SwiftUI
struct ForegroundPresentationDemo: View {
@State private var last: String = "(none)"
var body: some View {
VStack(spacing: 12) {
Text("Last received: \(last)")
Button("Simulate Delivery") {
last = Date().formatted()
}
Text("Tip: Use UNUserNotificationCenterDelegate in your app to choose banner/sound when active.")
.font(.footnote)
.foregroundStyle(.secondary)
}
.padding()
}
}
گرفتن مجوز و ثبت برای پوش
پس از اجازه، در APNs ثبت نام کن. سپس توکن دستگاه را بگیر.
import SwiftUI
import UserNotifications
import UIKit
@main
struct MyApp: App {
init() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Device token: \(deviceToken)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("APNs registration failed: \(error)")
}
}
پل SwiftUI App و AppDelegate
برای دریافت کال بک ها، نماینده را متصل کن. سپس نماینده اعلان را هندل کند.
import SwiftUI
import UserNotifications
import UIKit
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
UNUserNotificationCenter.current().delegate = appDelegate
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
کنترل نمایش و واکنش کاربر
با UNUserNotificationCenterDelegate نمایش را در فورگراند مشخص کن. سپس روی تپ ها مسیر بده.
import UserNotifications
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Navigate using response.notification.request.content.userInfo
completionHandler()
}
}
دسته بندی ها و اکشن ها
اکشن ها دکمه های اعلان هستند. کاربر سریع پاسخ می دهد. سپس نتیجه را هندل کن.
import UserNotifications
let reply: UNTextInputNotificationAction = UNTextInputNotificationAction(identifier: "REPLY", title: "Reply", options: [])
let mark: UNNotificationAction = UNNotificationAction(identifier: "MARK", title: "Mark Read", options: [.authenticationRequired])
let category: UNNotificationCategory = UNNotificationCategory(identifier: "MESSAGE", actions: [reply, mark], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
// Include "category": "MESSAGE" in APNs payload.
آزمایش و عیب یابی
- شبیه ساز پوش ریموت نمی گیرد. دستگاه واقعی لازم است.
- توکن سندباکس با تولیدی فرق دارد. محیط را منطبق کن.
- کلید APNs معتبر باشد. تیم و شناسه ها درست باشند.
- قابلیت Push فعال باشد. برای به روزرسانی، Remote notifications را بزن.
- اندازه پیلود محدود است. لاگ دستگاه را در Xcode ببین.
نکته: برای مسیر کامل حریم خصوصی، صفحه حریم خصوصی و مجوزها را ببین. برای سناریوهای تست، به تست SwiftUI سر بزن. برای ویجت ها، صفحه ویجت ها و اکستنشن ها مفید است.
جمع بندی سریع
- اول اجازه اعلان پوش را بگیر.
- بعد ثبت نام در APNs انجام بده.
- نمایش فورگراند را دلخواه کن.
- اکشن ها را با Category فعال کن.
- روی دستگاه واقعی تست کن.