天天看點

swift3.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: )]

        //極光推送;

       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=

        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 , *)
    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":,"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 ?? ,"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的路上,坑很多,有時間和大家一起分享。