Swift之一次性通知,定时通知,远程推送全解

在Swift开发中,可以使用UNUserNotificationCenter来添加一次性通知和定时通知。下面是一个简单的示例代码,演示如何添加一次性通知和定时通知:

  1. 导入UserNotifications框架,并请求用户授权通知权限。

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 请求授权通知权限
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                print("Error requesting authorization for notifications: \(error.localizedDescription)")
            }
        }
        
        // 设置UserNotificationCenter的代理
        UNUserNotificationCenter.current().delegate = self
    }

    // 实现UserNotificationCenter的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 处理用户对通知的响应
        completionHandler()
    }
}

  1. 添加一次性通知。

func addOneTimeNotification() {
    let content = UNMutableNotificationContent()
    content.title = "One Time Notification"
    content.body = "This is a one time notification."
    content.sound = .default
    
    // 通知触发时间为当前时间加上10秒
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
    
    let request = UNNotificationRequest(identifier: "OneTimeNotification", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error {
            print("Error adding one time notification: \(error.localizedDescription)")
        } else {
            print("One time notification added successfully.")
        }
    }
}

  1. 添加定时通知。

func addScheduledNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Scheduled Notification"
    content.body = "This is a scheduled notification."
    content.sound = .default
    
    // 设置每周三晚上8点触发通知
    var dateComponents = DateComponents()
    dateComponents.weekday = 4
    dateComponents.hour = 20
    dateComponents.minute = 0
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    
    let request = UNNotificationRequest(identifier: "ScheduledNotification", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error {
            print("Error adding scheduled notification: \(error.localizedDescription)")
        } else {
            print("Scheduled notification added successfully.")
        }
    }
}


关于UNUserNotificationCenter.current().delegate = self

设置一个代理对象并实现相应的方法,可以让我们在通知发送、接收和处理时获取更多的信息和控制。下面是列出所有UNUserNotificationCenterDelegate代理方法并对其进行详细解读:

以下是 UNUserNotificationCenterDelegate 协议中的方法列表:

  1. userNotificationCenter(_:willPresent:withCompletionHandler:)

    • 描述:在通知即将展示给用户时调用此方法。
    • 参数:
      • center:通知中心对象。
      • notification:待展示的通知对象。
      • completionHandler:完成处理的闭包,在闭包中指定展示通知的方式。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
          // 在这里处理通知的展示方式
          completionHandler([.banner, .badge, .sound])
      }
      
  2. userNotificationCenter(_:didReceive:withCompletionHandler:)

    • 描述:当接收到通知时调用此方法,不论是在前台还是后台。
    • 参数:
      • center:通知中心对象。
      • response:包含接收到的通知和用户的响应信息的对象。
      • completionHandler:完成处理的闭包,在闭包中指定对通知的处理结果。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
          // 在这里处理通知的响应
          completionHandler()
      }
      
  3. userNotificationCenter(_:openSettingsFor:)

    • 描述:当用户点击通知设置按钮时调用此方法。
    • 参数:
      • center:通知中心对象。
      • notification:被点击的通知对象。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
          // 在这里处理通知设置按钮的点击事件
      }
      
  4. userNotificationCenter(_:didReceive:attachmentOptions:withCompletionHandler:)

    • 描述:当接收到带附件的通知时调用此方法。
    • 参数:
      • center:通知中心对象。
      • response:包含接收到的通知和用户的响应信息的对象。
      • options:附件的选项。
      • completionHandler:完成处理的闭包,在闭包中指定对通知的处理结果。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, attachmentOptions options: [UNNotificationAttachmentOptionsKey : Any], withCompletionHandler completionHandler: @escaping () -> Void) {
          // 在这里处理带附件的通知的响应
          completionHandler()
      }
      
  5. userNotificationCenter(_:willPresent:for:)

    • 描述:当通知将要在指定的应用程序状态下展示时调用此方法。
    • 参数:
      • center:通知中心对象。
      • notification:待展示的通知对象。
      • applicationState:应用程序的状态。
    • 返回值:展示通知的选项。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, for applicationState: UIApplicationState) -> UNNotificationPresentationOptions {
          // 在这里指定通知展示的方式
          return [.alert, .sound]
      }
      
  6. userNotificationCenter(_:didReceive:withCompletionHandler:)

    • 描述:当接收到通知时调用此方法,不论是在前台还是后台。
    • 参数:
      • center:通知中心对象。
      • response:包含接收到的通知和用户的响应信息的对象。
      • completionHandler:完成处理的闭包,在闭包中指定对通知的处理结果。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
          // 在这里处理通知的响应
          let requestData = response.notification.request.content.userInfo
          if let customData = requestData["customData"] as? String {
              print("接收到自定义数据:\(customData)")
          }
          completionHandler()
      }
      
    • 解读:该方法在接收到通知并且用户响应了该通知时调用。通过 response 参数可以获取到通知的内容和用户的响应信息。在这个例子中,我们通过访问 userInfo 字典来获取自定义数据,并进行相应的处理。
  7. userNotificationCenter(_:openSettingsFor:)

    • 描述:当用户点击通知设置按钮时调用此方法。
    • 参数:
      • center:通知中心对象。
      • notification:被点击的通知对象。
    • 返回值:无。
    • 代码示例:
      func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
          // 在这里处理通知设置按钮的点击事件
          if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
              UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
          }
      }
      

UNUserNotificationCenter 是用于管理应用程序的通知中心,它提供了一系列属性和方法来管理和处理通知。

以下是 UNUserNotificationCenter 类的常用属性和方法以及它们的详细解读和代码实现:

属性(Properties)

  1. current
    • 描述:获取当前应用程序的通知中心对象。
    • 代码实现:
      let center = UNUserNotificationCenter.current()
      

方法(Methods)

  1. getNotificationSettings(completionHandler:)

    • 描述:获取应用程序的通知设置。
    • 参数:
      • completionHandler:完成处理的闭包,在闭包中获取通知设置信息。
    • 返回值:无。
    • 代码实现:
      UNUserNotificationCenter.current().getNotificationSettings { settings in
          print("通知设置:\(settings)")
      }
      
  2. requestAuthorization(options:completionHandler:)

    • 描述:请求用户授权进行通知推送。
    • 参数:
      • options:请求授权的选项,如 .badge, .sound, .alert 等。
      • completionHandler:授权请求的结果处理闭包。
    • 返回值:无。
    • 代码实现:
      UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
          if granted {
              print("用户已授权通知")
          } else {
              print("用户未授权通知")
          }
      }
      
  3. add(request:withCompletionHandler:)

    • 描述:向通知中心添加一个通知请求。
    • 参数:
      • request:要添加的通知请求对象。
      • completionHandler:添加完成的处理闭包。
    • 返回值:无。
    • 代码实现:
      let content = UNMutableNotificationContent()
      content.title = "新消息"
      content.body = "您有一条新消息"
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
      let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)
      
      UNUserNotificationCenter.current().add(request) { error in
          if let error = error {
              print("添加通知请求失败:\(error.localizedDescription)")
          } else {
              print("通知请求添加成功")
          }
      }
      
  4. removePendingNotificationRequests(withIdentifiers:)

    • 描述:移除指定标识符的待发送通知请求。
    • 参数:
      • identifiers:要移除的通知请求的标识符数组。
    • 返回值:无。
    • 代码实现:
      UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification1", "notification2"])
      
  5. removeDeliveredNotifications(withIdentifiers:)

    • 描述:移除指定标识符的已经发送的通知。
    • 参数:
      • identifiers:要移除的通知的标识符数组。
    • 返回值:无。
    • 代码实现:
      UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notification1", "notification2"])
      
  6. getNotificationCategories(completionHandler:)

    • 描述:获取应用程序当前注册的通知分类。
    • 参数:
      • completionHandler:完成处理的闭包,在闭包中获取通知分类信息。
    • 返回值:无。
    • 代码实现:
      UNUserNotificationCenter.current().getNotificationCategories { categories in
          print("已注册的通知分类:\(categories)")
      }
      
  7. setNotificationCategories(_:)

    • 描述:设置应用程序的通知分类。
    • 参数:
      • categories:要设置的通知分类集合。
    • 返回值:无。
    • 代码实现:
      let category = UNNotificationCategory(identifier: "myCategory", actions: [], intentIdentifiers: [], options: [])
      UNUserNotificationCenter.current().setNotificationCategories([category])
      
  8. delegate

    • 描述:通知中心的代理对象,用于处理通知相关的事件和回调。
    • 代码实现:
      UNUserNotificationCenter.current().delegate = self
      
  9. add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: ((Error?) -> Void)?)

    • 描述:添加一个通知请求,并指定完成处理的闭包。
    • 参数:
      • request:要添加的通知请求对象。
      • completionHandler:添加完成的处理闭包。
    • 返回值:无。
  10. getDeliveredNotifications(completionHandler:)

  • 描述:获取已经发送的通知列表。
  • 参数:
    • completionHandler:完成处理的闭包,在闭包中获取已发送通知的列表。
  • 返回值:无。
  • 代码实现:
    UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
        for notification in notifications {
            print(notification.request.identifier)
        }
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容