iOS開(kāi)發(fā) swift -- JPush極光推送的使用

一 APNS推送機(jī)制

1、 官方解釋如下圖


推送.jpg
圖中,Provider是指某個(gè)iPhone軟件的Push服務(wù)器。

APNS 是Apple Push Notification Service(Apple Push服務(wù)器)的縮寫,是蘋果的服務(wù)器。
上圖可以分為三個(gè)階段。
第一階段:服務(wù)器把要發(fā)送的消息、目的iPhone的標(biāo)識(shí)打包,發(fā)給APNS。
第二階段:APNS在自身的已注冊(cè)Push服務(wù)的iPhone列表中,查找有相應(yīng)標(biāo)識(shí)的iPhone,并把消息發(fā)到iPhone。
第三階段:iPhone把發(fā)來(lái)的消息傳遞給相應(yīng)的應(yīng)用程序, 并且按照設(shè)定彈出Push通知。

2、 詳細(xì)工作流程


推送.jpg
根據(jù)圖片我們可以概括一下:

a、應(yīng)用程序注冊(cè)APNS消息推送。
b、iOS從APNS Server獲取devicetoken,應(yīng)用程序接收device token。
c、應(yīng)用程序?qū)evice token發(fā)送給程序的PUSH服務(wù)端程序。
d、服務(wù)端程序向APNS服務(wù)發(fā)送消息。
e、APNS服務(wù)將消息發(fā)送給iPhone應(yīng)用程序。

二 注冊(cè)證書(shū)

詳細(xì)步驟

三 SDK 集成 CocoaPods

$ cd/你的項(xiàng)目地址
$ open -e Podfile

target 'zanqian' do
  pod 'JPush', '~> 3.0.0'
 end

$ pod install

四 代碼示例

1、基本配置

    //appdelegate.swift 遵循 JPUSHRegisterDelegate
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // 極光
        if #available(iOS 10.0, *) {
            let entity = JPUSHRegisterEntity()
            entity.types = Int(UNAuthorizationOptions.alert.rawValue|UNAuthorizationOptions.badge.rawValue|UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        }else {
            let types = UIUserNotificationType.badge.rawValue |
            UIUserNotificationType.sound.rawValue |
            UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }
        JPUSHService.setup(withOption: launchOptions, appKey: "", channel: "app store", apsForProduction: false)

        // 獲取遠(yuǎn)程推送消息 iOS 10 已取消
        let remote = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? Dictionary<String,Any>;
        // 如果remote不為空,就代表應(yīng)用在未打開(kāi)的時(shí)候收到了推送消息
        if remote != nil {
            // 收到推送消息實(shí)現(xiàn)的方法 
           }

         //自定義消息 需要自己在receiveNotification中自己實(shí)現(xiàn)消息的展示
         NotificationCenter.default.addObserver(self, selector: #selector(receiveNotification(notification:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
    }

    //注冊(cè)APNs成功并上報(bào)DeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        debugPrint("極光注冊(cè)失敗",error.localizedDescription)
    }

2、代理回調(diào)

    // 接收到消息回調(diào)方法
    @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)
        }else {
            //本地通知
        }
        //需要執(zhí)行這個(gè)方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以選擇設(shè)置
        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)
        }else {
            //本地通知
        }
        //處理通知 跳到指定界面等等
        receivePush(userInfo as! Dictionary<String, Any>)
        completionHandler()
    }

    // iOS 9.0 
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo);
        completionHandler(UIBackgroundFetchResult.newData);
    }

3、推送處理

    func receivePush(_ userInfo : Dictionary<String,Any>) {
        //根據(jù)服務(wù)器返回的字段判斷
        let userInfo = userInfo["key"] as! String
        let jsonData:Data = userInfo.data(using: .utf8)!
        var dict = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:AnyObject]
        let messageJson = JSON(dict ["data"]!)
        let message = Message.init(json: messageJson)
        if message.type == 2
        {
            let rootView = getRootViewController()
            rootView.pushViewController(MessageViewController.init(type: 2), animated: true)
        }
        // 角標(biāo)變0
        UIApplication.shared.applicationIconBadgeNumber = 0
    }


    //獲取當(dāng)前頁(yè)面的是控制器
    func getRootViewController () ->(UINavigationController)
    {
        let rootViewController = UIApplication.shared.keyWindow?.rootViewController
        if (rootViewController?.isKind(of: TabBarViewController.self))!
        {
            //let firstController = rootViewController?.childViewControllers[tabBarController.selectedIndex]
            let firstController = tabBarController.selectedViewController
            if (firstController?.isKind(of: UINavigationController.self))! {
                return firstController as! UINavigationController
            }else
            {
                return UINavigationController.init(rootViewController: firstController!)
            }
        }else if (rootViewController?.isKind(of: UINavigationController.self))!
        {
            return rootViewController as! UINavigationController
        }
        
        return UINavigationController.init(rootViewController: rootViewController!)
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
      //角標(biāo)至0
      UIApplication.shared.applicationIconBadgeNumber = 0
    }

如有不妥,請(qǐng)多多指教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容