Swift에서 극광 Push 구성

5110 단어
iOS 10 이하 시스템에는 적합하므로 극광 푸시를 구성할 때 몇 가지 작업이 필요합니다.먼저 코드를 올리고 이따가 천천히 말하거나 문제가 있으면 아래에 메시지를 남겨도 됩니다.물론 제가 쓴 것도 표준에 맞지 않는 부분이 있으니 여러분의 많은 가르침을 바랍니다.다음 코드
import UIKit


//iOS        
let iOS_Version:Float = Float.init(UIDevice.current.systemVersion)!
let iOS10 = (iOS_Version >= 10.0)
let iOS8 = (iOS_Version >= 8.0)

@UIApplicationMain


class AppDelegate: UIResponder, UIApplicationDelegate{

    var window: UIWindow?
    let testValue = true
    private let PushKey = "xxx"
    private let channel = "App Store"
    private let isProduction = false



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.white
        self.window?.makeKeyAndVisible()

        self.registerForAPNs(launchOptions)
        self.rootVCAndLoginVCSettings()
        
        return true
    }

    func rootVCAndLoginVCSettings() {
        let loginViewController     = LoginViewController()
        let rootViewController      = RootViewController()
        let navigationController    = UINavigationController()
        navigationController.pushViewController(rootViewController, animated: true)
        self.window?.rootViewController = self.testValue ? navigationController:loginViewController
    }

    //MARK:      
    func registerForAPNs(_ launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {

        //      
        if #available(iOS 10.0, *) {
            let entity = JPUSHRegisterEntity.init()
            entity.types = Int(Double(JPAuthorizationOptions.alert.rawValue) + TimeInterval(JPAuthorizationOptions.badge.rawValue) + Double(JPAuthorizationOptions.sound.rawValue));
            JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self as JPUSHRegisterDelegate)
        }else if #available(iOS 8.0, *){
            JPUSHService.register(forRemoteNotificationTypes: UInt(Double(UIUserNotificationType.alert.rawValue) + TimeInterval(UIUserNotificationType.badge.rawValue) + Double(UIUserNotificationType.sound.rawValue)),
                                  categories: nil)
        }else{
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }

        JPUSHService.setup(withOption: launchOptions,
                           appKey: PushKey,
                           channel: channel,
                           apsForProduction: isProduction)

    }

    public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }

    public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Error:\(error)")
    }

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

    public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
}


extension AppDelegate : JPUSHRegisterDelegate{

    @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?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))//         ,        , Badge、Sound、Alert          
    }

    @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?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
}

위 코드에서 AppKey를 교체하면 바로 사용할 수 있습니다.우리는 직접 class AppDelegate: UIResponder, UIApplicationDelegate,JPUSHRegisterDelegate{ 방식으로 극광 전송 에이전트를 설정할 수 없다. 왜냐하면 안의 에이전트 방법은 iOS 10 SDK를 바탕으로 하는 것이기 때문에 직접 가져오면 낮은 버전SDK에서 컴파일되지 않는다.그래서 약간의 처리를 할 수 있고 위 코드의 방식으로 AppDelegate를 확장하여 문제를 해결할 수 있다.

좋은 웹페이지 즐겨찾기