iOS注册通知中心UserNotifications基础使用(Swift)

读完这篇文章你将了解到, 在项目开发中, 如何快速掌握消息推送的API调用, 完成本地通知的注册、消息的发送以及接受消息, 本文不做详细的关于推送的高级用法介绍, 仅为了能在日常开发中, 避免一些很基础的坑,在此记录一下而已

注册本地通知

便于观察我们在didFinishLaunchingWithOptions中完成通知注册:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    registerNotification(application)  
    return true
}

其中注册通知的方法实现如下:

func registerNotification(_ application: UIApplication) {
    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted: Bool, error: Error?) in
            DispatchQueue.main.async {
                if granted { application.registerForRemoteNotifications() }
            }
        }  
    } else {
        let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(settings)
    }

}

在AppDelegate中, 可以通过重写协议的方法, 来接收通知注册成功或失败的结果:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    //TODO: 注册远程通知, 将deviceToken传递过去
    //registerAPS(with: deviceToken.hexString)
}
    
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    //TODO: 注册失败后的结果, 可以在这里记录失败结果, 以后再伺机弹框给用户打开通知
}

发送本地通知

通常我们需要调用本地通知, 来提醒用户进行某项操作, 这里要注意一下, 传递消息的userInfo仅支持基础类型(String, Float, Int, Data, Date)当做value, 不支持自定义类型

class Sender {
    var id: String
}

❎这种方式会引起崩溃 
UIApplication.localNotification(title: "标题", body: "内容", userInfo: ["sender": sender])
✅将消息内容单独作为Key发送 
UIApplication.localNotification(title: "标题", body: "内容", userInfo: ["sender": sender.id])

方法实现如下:

extension UIApplication {
    public static func localNotification(title: String, body: String, dateComponents: DateComponents? = nil, userInfo : [AnyHashable : Any]? = nil) {
        if #available(iOS 10, *) {
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.userInfo = userInfo ?? [:]
        
            var trigger: UNNotificationTrigger?
            if let dataCompontnts = dateComponents {
                trigger = UNCalendarNotificationTrigger(dateMatching: dataCompontnts, repeats: false)
            }
        
            let request = UNNotificationRequest(identifier: "id", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
                //printLogDebug(error)
            })
        } else {
            let localNotification = UILocalNotification()
            localNotification.fireDate = dateComponents?.date ?? Date()
            localNotification.alertBody = body
            localNotification.alertTitle = title
            localNotification.userInfo = userInfo
            localNotification.timeZone = NSTimeZone.default
            localNotification.soundName = UILocalNotificationDefaultSoundName
            UIApplication.shared.scheduleLocalNotification(localNotification)
        }
    }
}
        

接收消息的推送通知

苹果工程师在iOS10版本为我们设计了全新的通知中心, 为了兼容以前的版本, 在有消息推送过来时要考虑到在两个地方都要处理, 这里我通过onResponseNotification方法统一接收消息回调:

//iOS10以下接收消息的回调
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable:Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    //TODO: 接收通知的回调, 当用户点击通知栏, 会调起这里, iOS10以上的系统专门增加了一个协议方法处理, 这里做主要是兼容iOS10以下的设备
    onResponseNotification(userInfo: userInfo)
    completionHandler(.newData)
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    @available(iOS 10.0, *)
    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        onResponseNotification(userInfo: response.notification.request.content.userInfo)
        completionHandler()
    }
    
}

//接收通知的回调方法, 有两个地方会调用此方法, 接收推送的通知在iOS10以上版本和iOS以下版本都要进行处理
private func onResponseNotification(userInfo: userInfo) {
    guard let content = userInfo["****"] as? String {
        return 
    }
    //TODO: 通过点击通知栏进入App后,打开收到的消息, 做跳转处理
}

以上是作为平时开发中, 需要经常使用到的方法, 当然关于UNUserNotificicationCenter的用法还有很多, 网上也可以找到类似的文章,这里我就不详细翻开来说了, 有遇到问题的朋友欢迎在下面留言, 一起讨论下.

你可能感兴趣的:(iOS注册通知中心UserNotifications基础使用(Swift))