swift3.0实现极光推送和自定义消息

9 篇文章 0 订阅

最近在写一个纯的swift项目,虽然swift还是非常的完美,但是由于对它不够熟悉,遇到了很多的坑,这一次分享一下极光的推送的使用的,
关于极光推送的自定义消息,我也解释过的,在我之前的博客中,这一次主要分享一下,如何用swift3.0实现极光推送和自定义的消息
关于极光SDK的集成,和OC的没有区别,官方的资料也很详细,我在这里不讲了,
直接上代码代码

//  Created by 段振轩 on 2016/12/26.
//  Copyright © 2016年 段振轩. All rights reserved.
//

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate,BMKGeneralDelegate,UIAlertViewDelegate {


    var window: UIWindow?
    var _mapManager: BMKMapManager?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


        // 要使用百度地图,请先启动BaiduMapManager
        _mapManager = BMKMapManager()
        // 如果要关注网络及授权验证事件,请设定generalDelegate参数
        let ret = _mapManager?.start("RXn7z14wXaiX82uG6VzxnSIhMSoYzeRt", generalDelegate: self)
        if ret == false {
            NSLog("manager start failed!")
        }








        //UINavigationBar.appearance().titleTextAttributes=NSDictionary(object:UIColor.white, forKey:NSForegroundColorAttributeName as NSCopying) as? [String : AnyObject];
        //UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.boldSystemFont(ofSize: 20)]




        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.systemFont(ofSize: 19)]

        //极光推送;

       JPUSHService.register(forRemoteNotificationTypes: (UIUserNotificationType.badge.union(UIUserNotificationType.sound).union(UIUserNotificationType.alert)).rawValue, categories:nil)


        JPUSHService.setup(withOption: launchOptions, appKey:"6a9350d7afdda858e41f59f9", channel:"", apsForProduction:true)


//        let center : UNUserNotificationCenter = UNUserNotificationCenter
        //注册一个通知,我们从通知拿到registID
        NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.self.networkDidLogin(notification:)), name: NSNotification.Name.jpfNetworkDidLogin, object: nil)
        return true
    }
    //在这里拿到divieToken 向极光注册拿到registID;拿到registID后可能需要上传到您的应用服务器,
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        print("divceToken"+"\(deviceToken)");

        JPUSHService.registerDeviceToken(deviceToken)


    }

    //在这个通知的方法中,就可以拿到我们想要的registID
    public func networkDidLogin(notification:NSNotification){

        if (JPUSHService.registrationID() != nil) {


            let str:String = JPUSHService.registrationID()

            print("registId:"+str);

            if UserAccount.isLogin() {

                saveDivce(registid: str)
            }



        }



    }







    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {


        print("接到通知")

        JPUSHService.handleRemoteNotification(userInfo)

        application.applicationIconBadgeNumber=0

        JPUSHService.resetBadge()

        if(application.applicationState == .active) {

            //在前台活动do nothing

            let alertView = UIAlertView(title: "消息", message: "您有一条新的消息", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "查看")

            alertView.show()

        }else{

            //后台或者没有活动

        }




    }




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


}


//极光推送的代理方法

extension AppDelegate:JPUSHRegisterDelegate{


    @available(iOS 10.0, *)
    public func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {

    }
    public func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {

    }


}





extension AppDelegate{

    func saveDivce(registid:String) {

        let paramers = ["plateform":1,"registrationId":registid] as [String : Any]

        NetworkToolRequest.SaveDivice(params: paramers as [String : AnyObject]) { (response) in
            print("上传结果"+"\(response)")

            self.DivceRelation(registid: registid)

        }

    }

    func DivceRelation(registid:String) {

        let paramers = ["memberId":UserAccount.account?.id ?? 0,"registrationId":registid] as [String : Any]

        NetworkToolRequest.RelationDivice(params: paramers as [String : AnyObject]) { (response) in
             print("绑定结果"+"\(response)")

        }

    }


}

//下面的代码是接受一个自定义消息的,自定义的消息,只能在前台运行,为了能够接受到自定义消息,建议还写自己的根控制器中,tabbar,这种不会销毁的控制器中。

接收自定义消息,通过注册通知,接受到消息的内容,其实被套了一层壳,如果直接通过key的方式,拿到这个字典的key是不行的。必须要将通知的内容,转成data.再通过反序列化为为字典,这个坑,我也被坑了一下午的。

//  Created by 段振轩 on 2017/2/23.
//  Copyright © 2017年 段振轩. All rights reserved.
//

import UIKit

let identifier = "MainCell"

class GrabOrderTableViewController: UITableViewController {


    var orders :[GrabOrder] = [GrabOrder]()


    override func viewDidLoad() {
        super.viewDidLoad()

//        self.view.backgroundColor = UIColor.red;

        NotificationCenter.default.addObserver(self, selector: #selector(self.networkDidReceiveMessage(notification:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)


        setUpTableView()

    }
    func networkDidReceiveMessage(notification:NSNotification){


        //注意拿到通知的内容,一定要转成二进制。
        var userInfo =  notification.userInfo!
        //获取推送内容
        let content =  userInfo["content"] as! String

        let data = content.data(using: .utf8)
        let dic = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)

        //将这个字典转成模型,显示到我们的界面,这个功能就完成。
        let order = GrabOrder.init(Dic: dic as! [String : AnyObject])

        orders.append(order)


        tableView.reloadData()






    }

就写这么多吧,swift的路上,坑很多,有时间和大家一起分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值