Swift 3.0 集成极光推送

本文介绍如何使用Swift语言集成极光推送服务,包括配置步骤、关键代码实现及注意事项。适用于iOS应用开发者。

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))// 需要执行这个方法,选择是否提醒用户,有badgesoundalert三种类型可以选择设置
    }

    @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,收不到推送消息

<think>好的,我现在需要帮用户解决在Swift 5项目中集成极光推送的问题。用户之前已经得到过详细的步骤,现在再次提问,可能希望获得更清晰的指导或者补充信息。首先,我需要回顾之前的回答,确保这次回答的一致性,同时检查是否有遗漏或需要优化的地方。 用户提供的引用内容中,引用[3]提到了配置文件的位置,比如Info.plist、AppDelegate.swift、Podfile等,这些在之前的回答中都有涉及。引用[4]是关于package.json的配置,但用户的项目是Swift,可能不太相关,不过需要注意是否需要其他配置文件。引用[1]和[2]是关于Swift的资源和第三方库,可能对用户有帮助,可以适当提及。 接下来,我需要确保回答结构清晰,步骤正确。之前的步骤包括配置环境、初始化JPush、处理推送消息。现在可能需要补充更多细节,比如如何获取AppKey,处理权限请求,以及测试推送的步骤。 用户可能遇到的问题包括:如何正确配置Podfile,处理权限请求的代码是否完整,如何处理后台和前台的通知,以及如何测试推送是否成功。需要检查代码示例是否正确,尤其是Swift 5的语法和JPush的最新SDK版本。 另外,用户可能希望了解如何处理自定义通知样式或者调试推送问题,这些可以作为相关问题提出。同时,确保引用正确的参考资料,比如引用[3]提到的Podfile和AppDelegate的配置,引用[1]中的资源可能对用户深入学习有帮助。 需要验证代码示例是否正确,比如JPUSHService的初始化方法是否正确,是否需要在AppDelegate中实现UNUserNotificationCenterDelegate的方法。同时,确保用户知道替换自己的AppKey,并正确配置Capabilities中的推送通知。 最后,检查回答是否符合系统级指令,如使用正确的中文,LaTeX格式,引用标识等。确保相关问题部分有针对性,帮助用户进一步解决问题。</think>根据您提供的引用内容和历史交互记录,以下是针对 Swift 5 集成极光推送(JPush)的完整指南: --- ### Swift 5 集成 JPush 完整指南 #### 一、环境配置 1. **添加 CocoaPods 依赖** 根据引用[3]中的 `Podfile` 配置建议,修改您的依赖文件: ```ruby platform :ios, &#39;11.0&#39; # iOS版本需≥9.0 use_frameworks! target &#39;YourProject&#39; do pod &#39;JPUSHService&#39;, &#39;~> 4.6.0&#39; # 2023年最新稳定版 end ``` 执行 `pod install` 后重启 `.xcworkspace` 文件[^3]。 2. **配置 AppKey 和权限** 在 `Info.plist` 中添加极光推送的权限声明(引用[3]): ```xml <key>JPUSHAppKey</key> <string>your_app_key</string> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> ``` #### 二、核心初始化代码 1. **AppDelegate 基础配置** ```swift import UIKit import UserNotifications import JPUSHService @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 初始化极光推送 let config = JPUSHRegisterEntity() config.types = JPAuthorizationOptions([.alert, .badge, .sound]).rawValue JPUSHService.setup(withOption: launchOptions, appKey: "your_app_key", channel: "App Store", apsForProduction: false) // 开发环境设为false // 注册通知权限 UNUserNotificationCenter.current().delegate = self requestNotificationAuthorization() return true } } ``` 2. **权限请求方法** ```swift private func requestNotificationAuthorization() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } } ``` #### 三、设备令牌处理 ```swift // 获取DeviceToken func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { JPUSHService.registerDeviceToken(deviceToken) let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() print("APNs Device Token: \(token)") } // 注册失败处理 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("APNs注册失败: \(error.localizedDescription)") } ``` #### 四、推送消息处理 ```swift extension AppDelegate: JPUSHRegisterDelegate { // 前台收到推送 func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) { let userInfo = notification.request.content.userInfo JPUSHService.handleRemoteNotification(userInfo) completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue)) } // 点击推送 func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) { let userInfo = response.notification.request.content.userInfo JPUSHService.handleRemoteNotification(userInfo) completionHandler() } } ``` #### 五、关键配置验证 1. **Capabilities 配置** 在 Xcode 项目中启用: - Push Notifications - Background Modes → Remote notifications 2. **环境检查** 添加调试代码验证注册状态: ```swift JPUSHService.registrationIDCompletionHandler { resCode, registrationID in print("极光注册ID: \(registrationID ?? "nil")") } ``` --- ### 常见问题解决 1. **收不到推送** - 检查 `AppKey` 是否与极光控制台一致 - 确保设备网络可访问 `jpush.cn` 域名 - 使用 `JPUSHService.setLogLevel(.debug)` 开启调试日志 2. **后台推送处理** 如需处理静默推送,需在 `Background Modes` 中勾选 `Background fetch`,并实现: ```swift func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { JPUSHService.handleRemoteNotification(userInfo) completionHandler(.newData) } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值