Swift3.0 集成极光推送

作者: calary | 来源:发表于2017-03-14 23:32 被阅读1125次

    1.前言

    推送证书配置什么的都不多讲了,极光推送的开发文档里都有详细的介绍极光推送文档,因为官方的文档是OC版本的,我这里主要是讲解一下怎么用Swift进行集成。

    2.配置

    现在一切都已经根据他们的文档配置好了,就剩下代码转化了
    第一步
    在桥接文件xx-Bridging-Header.h里加入以下代码

    // 引入JPush功能所需头文件
    #import "JPUSHService.h"
    // iOS10注册APNs所需头文件
    #ifdef NSFoundationVersionNumber_iOS_9_x_Max
    #import <UserNotifications/UserNotifications.h>
    #endif
    // 如果需要使用idfa功能所需要引入的头文件(可选)
    #import <AdSupport/AdSupport.h>
    

    第二步

     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            
            //省略其它代码......
    
            //极光推送部署
            let entity = JPUSHRegisterEntity()
            entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.sound.rawValue | JPAuthorizationOptions.badge.rawValue)
            
            JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
            JPUSHService.setup(withOption: launchOptions, appKey: "1cbb0b714502d6add4f412ff", channel: "Publish channel", apsForProduction: JPUSH_IS_PRO) 
            
            JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
                if resCode == 0{
                    PrintLog("registrationID获取成功:\(registrationID)")
                }else {
                    PrintLog("registrationID获取失败:\(registrationID)")
                }
            }
            return true
        }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
            application.applicationIconBadgeNumber = 0
            application.cancelAllLocalNotifications()
        }
    
    //MARK:-极光推送 AppDelegate扩展
    extension AppDelegate:UNUserNotificationCenterDelegate,JPUSHRegisterDelegate
    {
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            
            JPUSHService.registerDeviceToken(deviceToken)
    //设置tags,后台可以根据这个来推送(本处用的是UserId)
            JPUSHService.setTags(["user"], aliasInbackground: UserHelper.getUserId())
            PrintLog("deviceToken:\(deviceToken)")
        }
        
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            PrintLog("did Fail To Register For Remote Notifications With Error:\(error)")
        }
        /**
         收到静默推送的回调
         
         @param application  UIApplication 实例
         @param userInfo 推送时指定的参数
         @param completionHandler 完成回调
         */
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            
            JPUSHService.handleRemoteNotification(userInfo)
            PrintLog("iOS7及以上系统,收到通知:\(userInfo)")
            completionHandler(UIBackgroundFetchResult.newData)
        }
        
        func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
            JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
        }
        
        @available(iOS 10.0, *)
        func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
            
            let userInfo = notification.request.content.userInfo
            
    //        let request = notification.request; // 收到推送的请求
    //        let content = request.content; // 收到推送的消息内容
    //        
    //        let badge = content.badge;  // 推送消息的角标
    //        let body = content.body;    // 推送消息体
    //        let sound = content.sound;  // 推送消息的声音
    //        let subtitle = content.subtitle;  // 推送消息的副标题
    //        let title = content.title;  // 推送消息的标题
            
            if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
                PrintLog("iOS10 前台收到远程通知:\(userInfo)")
                JPUSHService.handleRemoteNotification(userInfo)
            }else {
                // 判断为本地通知
                PrintLog("iOS10 前台收到本地通知:\(userInfo)")
            }
            completionHandler(Int(UNAuthorizationOptions.alert.rawValue | UNAuthorizationOptions.sound.rawValue | UNAuthorizationOptions.badge.rawValue))// 需要执行这个方法,选择是否提醒用户,有badge、sound、alert三种类型可以选择设置
        }
        
        @available(iOS 10.0, *)
        func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
            let userInfo = response.notification.request.content.userInfo
            
            if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
                PrintLog("iOS10 收到远程通知:\(userInfo)")
                JPUSHService.handleRemoteNotification(userInfo)
            }
            completionHandler()
        }
    }
    
    

    完成!

    3.总结

    本文只是简单的集成了极光推送,亲测可用,具体的细节型的功能没有 去发掘,以后遇到了需求再进行更新,希望可以帮到你😄。
    如果你发现第一次开启后无法收到推送消息,请参考【极光推送】第一次打开app,收不到推送消息

    相关文章

      网友评论

        本文标题:Swift3.0 集成极光推送

        本文链接:https://www.haomeiwen.com/subject/qguknttx.html