swift3 激光推送的消息推送和接收

本文详细介绍如何在iOS应用中集成激光推送服务,包括不同iOS版本下的初始化配置、设备令牌注册及推送消息处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、集成激光推送

网上很多教程,这里略

二、激光初始化

在AppDelegate.swift文件中加入以下代码

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        if #available(iOS 10, *) {
            let entity = JPUSHRegisterEntity()
            entity.types = NSInteger(UNAuthorizationOptions.alert.rawValue) |
                NSInteger(UNAuthorizationOptions.sound.rawValue) |
                NSInteger(UNAuthorizationOptions.badge.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
            
        } else if #available(iOS 8, *) {
            // 可以自定义 categories
            JPUSHService.register(
                forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
                    UIUserNotificationType.sound.rawValue |
                    UIUserNotificationType.alert.rawValue,
                categories: nil)
        } else {
            // ios 8 以前 categories 必须为nil
            JPUSHService.register(
                forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
                    UIRemoteNotificationType.sound.rawValue |
                    UIRemoteNotificationType.alert.rawValue,
                categories: nil)
        }
        
        JPUSHService.setup(withOption: launchOptions, appKey: appKey, channel: channel, apsForProduction: isProduction)
        
        // 获取推送消息
       
        return true
    }

以上代码设置好后,进行设置注册


func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("get the deviceToken  \(String(describing: deviceToken))")
        NotificationCenter.default.post(name: Notification.Name(rawValue: "didRegisterRemoteNotification"), object: deviceToken)
        JPUSHService.registerDeviceToken(deviceToken)
        var token = ""
        
        for i in 0..<deviceToken.count {
            //token += String(format: "%02.2hhx", arguments: [chars[i]])
            token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
        }
        
        print("Registration succeeded!")
        print("Token: ", token)
        
    }



ISO10及以上收到消息后走以下代码

//应用关闭或者在后台,收到扒推送时
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        print("Handle push from foreground")
        let userInfo: [AnyHashable:Any] = response.notification.request.content.userInfo;
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
            
        }
        JPUSHService.resetBadge()
        completionHandler();
        // 应用打开的时候收到推送消息
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "aaaaaaa"), object: nil, userInfo: userInfo)
     }
    //应用打开时,收到扒推送时
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo: [AnyHashable:Any] = notification.request.content.userInfo;
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        JPUSHService.resetBadge()
        //completionHandler();
        // 应用打开的时候收到推送消息
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "aaaaaaa"), object: nil, userInfo: userInfo)

    }



ISO9及以下收到消息后走以下代码

//iOS 10以下执行
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        //let alert: String = userInfo["aps"]!["alert"] as! String
        //var badge: Int = userInfo["aps"]!["badge"] as! Int
        //var badge: Int
        //badge -= 1
        //JPUSHService.setBadge(0)
        print("request message ok!")
        UIApplication.shared.applicationIconBadgeNumber = 0
        /**
         *  iOS的应用程序分为3种状态
         *      1、前台运行的状态UIApplicationStateActive;
         *      2、后台运行的状态UIApplicationStateInactive;
         *      3、app关闭状态UIApplicationStateBackground。
         */
        // 应用在前台 或者后台开启状态下,不跳转页面,让用户选择。
        if (application.applicationState == UIApplicationState.active) || (application.applicationState == UIApplicationState.background){
            //UIAlertView(title: "推送消息", message: "\(alert)", delegate: nil, cancelButtonTitle: "确定").show()
            UIAlertView(title: "推送消息", message: "\(userInfo)", delegate: nil, cancelButtonTitle: "确定").show()
        }else{
            //杀死状态下,直接跳转到跳转页面
        }
        // badge清零
        application.applicationIconBadgeNumber = 0
        JPUSHService.resetBadge()
        completionHandler(UIBackgroundFetchResult.newData)
        
        //把接收到的消息发送出去(发送到控制器,可以任意方法接收userInfo)
        //字符串responseName为本次发送的命称,接收时也要用该名称进行接收
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "responseName"), object: nil, userInfo: userInfo)
    }


消息发送重点一定要注意:

	//把接收到的消息发送出去(发送到控制器,可以任意方法接收userInfo)
        //字符串responseName为本次发送的命称,接收时也要用该名称进行接收
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "responseName"), object: nil, userInfo: userInfo)


消息接收

override func viewDidLoad() {
        super.viewDidLoad()
	//rawValue:为刚才发送消息时设置的名称
	//#selector:处理该消息的方法,这里用的是requestMsg
        NotificationCenter.default.addObserver(self, selector: #selector(requestMsg), name: Notification.Name.init(rawValue: "responseName"), object: nil)
        
    }
func requestMsg(notifi: NSNotification){
        let dicNotifi: [NSObject : AnyObject] = notifi.userInfo as! [NSObject : AnyObject]
        var json:JSON=JSON(dicNotifi)//这里用的swiftyJSON库
        /*
	print(json)
	消息处理过程,略
	*/
    }


最后还要移除通知

// 移除通知<通知移除是在发通知控制器中移除>
    deinit {
        //NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.removeObserver(observe!)
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值