iOS 集成极光推送 (swift版)

1 篇文章 0 订阅

iOS 集成极光推送 (swift版)

1、使用cocoapods安装极光推送SDK

之前项目使用的是信鸽推送,但是后面不知怎么地,就是收不到推送消息了,安卓,iOS都是,然后就换成了极光;
我用的是cocoapods安装,也可以在官网下载SDK拖拽进你的工程里
cocoapods安装及使用[https://www.jianshu.com/p/265d8e4dd73a]

在Podfile添加JPush

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
target '******' do
pod 'JPush' #极光推送
use_frameworks!
end

然后在终端进入你的项目目录,执行 pod install

2、注册及配置极光推送相关

在Header.h引入相关文件

#ifndef Header_h
#define Header_h
/*极光推送*/
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#endif /* Header_h */

AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
		//注册极光推送
		registerJPush()
		return true
	}
	func registerJPush(){
		//注册极光推送
        let entity = JPUSHRegisterEntity()
        entity.types = 1 << 0 | 1 << 1 | 1 << 2
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        //需要IDFA 功能,定向投放广告功能
        //let advertisingId = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        //通知类型(这里将声音、消息、提醒角标都给加上)
        let userSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound],
                                                      categories: nil)
        if ((UIDevice.current.systemVersion as NSString).floatValue >= 8.0) {
            //可以添加自定义categories
            JPUSHService.register(forRemoteNotificationTypes: userSettings.types.rawValue,
                                  categories: nil)
        }
        else {
            //categories 必须为nil
            JPUSHService.register(forRemoteNotificationTypes: userSettings.types.rawValue,
                                  categories: nil)
        }
        
        //监听自定义消息的接收
        //let defaultCenter =  NotificationCenter.default
        //defaultCenter.addObserver(self, selector: #selector(networkDidReceiveMessage(notification:)),
        //                          name:Notification.Name.jpfNetworkDidReceiveMessage, object: nil)
        
        JPUSHService.setup(withOption: launchOptions, appKey: "appKey", channel: "App Store", apsForProduction: false, advertisingIdentifier: nil)
	}
	
	//极光推送需要实现的代理方法
	// MARK: -JPUSHRegisterDelegate
    // iOS 10.x 需要
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    @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 is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 系统要求执行这个方法
        completionHandler()
    }
    
    //点推送进来执行这个方法
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        
    }
    //系统获取Token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UserDefaults.standard.set(deviceToken, forKey: "deviceToken")
        JPUSHService.registerDeviceToken(deviceToken)
    }
    //获取token 失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { //可选
        print("did Fail To Register For Remote Notifications With Error: \(error)")
    }
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        
    }

	func applicationDidEnterBackground(_ application: UIApplication) {
		//在应用进入后台时清除推送消息角标
        application.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
}

appKey在极光推送开发者服务平台里找,注册一个应用的时候会自动生成
在这里插入图片描述

3、使用别名做唯一标识推送到指定用户的设备

我这里使用的是登陆成功后接口返回的用户手机号做别名,seq是序列号,随便填,我这里用的是用户id

JPUSHService.setAlias("user\(loginInfo.telephone!)", completion: { (iResCode, iAlias, seq) in
                        print("iResCode---\(iResCode)")
                        print("iAlias---\(iAlias ?? "")")
                        print("seq---\(seq)")
                    }, seq: loginInfo.id!)

用户退出登录后移除别名,避免用户使用其他设备登录后当前设备依然还能收到推送消息

	JPUSHService.deleteAlias({ (iResCode, iAlias, seq) in
                print("iResCode---\(iResCode)")
                print("iAlias---\(iAlias ?? "")")
                print("seq---\(seq)")
            }, seq: Int(UserDefaults.standard.string(forKey: "userId")))
搞定!!!
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值