Swift项目集成极光推送SDK

极光推送在Objective-C项目下很容易集成,在基于Swift语言的项目就需要桥接来处理了,下面记录一下集成流程: (环境说明: XCode8.3.2,Swift3.0,iOS10)

1. 下载极光的开发SDK:

2. 项目增加JPush的开发库:

3. 在项目根目录的二级目录增加Swift调用OC的桥接文件文件名一般为<项目名>-Bridging-Header.h,如果在Swift项目新建OC的文件提示创建,这里是手动拉入文件的,因此按此一般约定创建一个就行,然后添加入项目工程:

4. 在项目的target里配置"Object-C Bridging Header"的引用路径:

5. 添加极光推送必要的framework:

-> CFNetwork.framwwork

-> CoreFoundation.framwwork

-> CoreTelephony.framwwork

-> SystemConfiguration.framwwork

-> CoreGraphics.framwwork

-> Foundation.framwwork

-> UIKit.framwwork

-> Security.framwwork

-> libz.tbd

-> AdSupport.framwwork(根据是否需要使用IDFA进行添加)

-> UserNotifications.framwwork(XCode8及以上需要)

-> libresolv.tbd(极光2.2.0以上需要,这里使用3.0.5的版本,因此需要添加)

添加完后如下:

6. 在桥接文件添加极光头文件的引用,其他OC文件也是类似import即可:

Build一下,没问题,继续下一步。

7. 在苹果开发者网站,生成针对该APP的开发和生产APNS证书,然后下载下来进行安装,安装后导出"*.p12"文件,用于上传到极光后台管理端,如下:

8. XCode配置:

对于XCode8以上,需要在项目target打开推送开关:

在配置"info.plit"支持http传输,ios虽然认只支持https传输,但是还有很多传输是http的,现在设置让其支持jpush的:

9. 在AppDelegate.swift添加逻辑处理:

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        application.statusBarStyle = UIStatusBarStyle.lightContent
        
        let navigationBarappearance = UINavigationBar.appearance()
        navigationBarappearance.isTranslucent = false
        navigationBarappearance.barTintColor = UIColor(hex: 0x25b6ed)
        navigationBarappearance.tintColor = UIColor.white
        navigationBarappearance.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
        
        registJPushRemoteNotification(launchOptions: (launchOptions==nil) ? [:] : launchOptions!)
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks,disable timers,and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources,save user data,invalidate timers,and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution,this method is called instead of applicationWillTerminate: when the user quits.
    }

    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.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was prevIoUsly in the background,optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    // MARK: APNS callback
    func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDevicetoken devicetoken: Data) {
        JPUSHService.registerDevicetoken(devicetoken)
    }
    
    func application(_ application: UIApplication,didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("[Error] Fail to register for remote notification with error: %@",error)
    }
    
    func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable : Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("[JPUSH Remote Noti receive]-> %@",userInfo)
    }
    
    // MARK: Delegate -> JPUSHRegisterDelegate
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!,didReceive response: UNNotificationResponse!,withCompletionHandler completionHandler: (() -> Void)!) {
        // iOS 10 Supported
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!,willPresent notification: UNNotification!,withCompletionHandler completionHandler: ((Int) -> Void)!) {
        // iOS 10 Supported
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNNotificationPresentationoptions.alert.rawValue))
    }
    

    // MARK: Private
    
    func registJPushRemoteNotification(launchOptions: [UIApplicationLaunchOptionsKey: Any]) {
        let jpushEntity = JPUSHRegisterEntity()
        jpushEntity.types = Int(JPAuthorizationoptions.alert.rawValue) + Int(JPAuthorizationoptions.badge.rawValue) + Int(JPAuthorizationoptions.sound.rawValue)
        //if Float(UIDevice.current.systemVersion)! >= Float(8.0) {
        //    // can definde a custom categories
        //}
        JPUSHService.register(forRemoteNotificationConfig: jpushEntity,delegate: self)
        JPUSHService.setup(withOption: (launchOptions==nil) ? [:] : launchOptions,appKey: JPUSH_APPKEY,channel: "APP Store",apsForProduction: false) // true - distribution  false - development
    }

10. 测试: 因为模拟器不支持获取远程推送,因此必须采用真机测试。

运行后发现如下错误

缺少配置,增加即可:

另外,launchOptions在用户启动是是空,由其他应用调起则有值,这里的Optional Value需要做判空处理,修改一下运行后日志如下,说明极光配置成功:

极光控制台发送一条信息看看(这里没有设置tag,因此所有APPkey一样的都会收到通知,后面再配置tag了)

点击发送,XCode的日志如下:

OK了,后面再根据需要完善其他逻辑即可。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...