阿里云SDK實(shí)現(xiàn)iOS10推送通知

原文鏈接

行文環(huán)境
- Xcode 10.1
- Swfit 4.1
- iOS 12
- 阿里云

證書(shū)設(shè)置

iOS推送證書(shū)設(shè)置

證書(shū)配置分為開(kāi)發(fā)環(huán)境和生產(chǎn)環(huán)境,需要與業(yè)務(wù)服務(wù)器的開(kāi)發(fā)環(huán)境(如dev/test)和正式環(huán)境區(qū)分開(kāi)。例如給測(cè)試分發(fā)的Ad Hoc包使用生產(chǎn)環(huán)境的證書(shū),但業(yè)務(wù)是test環(huán)境。

Ad Hoc包為什么收不到通知

因?yàn)锳d Hoc使用生產(chǎn)環(huán)境證書(shū),設(shè)備的deviceToken在不同證書(shū)環(huán)境是不同的,但測(cè)試包的業(yè)務(wù)是test環(huán)境,后臺(tái)會(huì)在test環(huán)境使用開(kāi)發(fā)的apns設(shè)置,導(dǎo)致deviceToken無(wú)法匹配到對(duì)應(yīng)的設(shè)備。

payload變化

老版本payload,只有body

{
    "aps": {
        "alert": {
        "your notification body",
        },
        "badge": 1,
        "sound": "default",
    },
    "key1":"value1",
    "key2":"value2"
}

新版payload,新增title、subtitle、body、category等字段

{
    "aps": {
        "alert": {
            "title": "title",
            "subtitle": "subtitle",
            "body": "body"
        },
        "badge": 1,
        "sound": "default",
        "category": "test_category",
        "mutable-content": 1
    },
    "key1":"value1",
    "key2":"value2"
}

業(yè)務(wù)邏輯字段方式?jīng)]有變化,直接加在json里

通知實(shí)現(xiàn)

初始化SDK

使用配置文件AliyunEmasServices-Info.plist直接調(diào)用autoInit

func setup(_ application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
    CloudPushSDK.autoInit { result in
        guard let result = result else {
            log.error("Push SDK init failed, error: result is nil!")
            return
        }
        if result.success {
            log.debug("Push SDK init success, deviceId: \(String(describing: CloudPushSDK.getDeviceId()))")
        } else {
            log.error("Push SDK init failed, error: \(String(describing: result.error))")
        }
    }

    //...
    // 點(diǎn)擊通知將App從關(guān)閉狀態(tài)啟動(dòng)時(shí),將通知打開(kāi)回執(zhí)上報(bào)
    CloudPushSDK.sendNotificationAck(launchOptions)
}

請(qǐng)求通知權(quán)限并注冊(cè)遠(yuǎn)程通知

第一次安裝會(huì)彈出請(qǐng)求通知的alert

func registerAPNS(application: UIApplication) {
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    var options: UNAuthorizationOptions = [.alert, .sound, .badge]
    if #available(iOS 12.0, *) {
        options = [.alert, .sound, .badge, .providesAppNotificationSettings]
    }
    center.requestAuthorization(options: options) { (granted, error) in
        if granted {
            log.debug("User authored notification.")
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        } else {
            log.debug("User denied notification.")
        }
        if let error = error {
            log.error(error)
        }
    }
}

注冊(cè)設(shè)備并上報(bào)deviceToken

func registerDevice(_ deviceToken: Data) {
    CloudPushSDK.registerDevice(deviceToken) { result in
        guard let result = result else {
            log.error("Register deviceToken failed, error:: result is nil!")
            return
        }
        if result.success {
            log.debug("Register deviceToken success, deviceToken: \(String(describing: CloudPushSDK.getApnsDeviceToken()))")
        } else {
            log.debug("Register deviceToken failed, error: \(String(describing: result.error))")
        }
    }
}

public func application(_ application: UIApplication,
                        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    registerDevice(deviceToken)
}

// 注冊(cè)失敗
public func application(_ application: UIApplication,
                        didFailToRegisterForRemoteNotificationsWithError error: Error) {
    log.error("did Fail To Register For Remote Notifications With Error : \(error)")
}

注冊(cè)通知類(lèi)別

通知類(lèi)別(category)用于給通知分類(lèi),可添加按鈕或自定義UI

func createCustomNotificationCategory() {
    let action = UNNotificationAction(identifier: "actionID", title: "buttonTitle", options: [])
    let category = UNNotificationCategory(identifier: "CategoryID", actions: [action],
                                          intentIdentifiers: [],
                                          options: .customDismissAction)
    UNUserNotificationCenter.current().setNotificationCategories([category])
}

UNUserNotificationCenterDelegate

UNUserNotificationCenterDelegate代替了UIAppDelegate的舊通知接收方法didReceiveRemoteNotification將接收通知的情況分為app開(kāi)啟時(shí)(foreground)和app不在前臺(tái)時(shí)(background)

// app打開(kāi)時(shí)調(diào)用
public func userNotificationCenter(_ center: UNUserNotificationCenter,
                                   willPresent notification: UNNotification,
                                   withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // 業(yè)務(wù)邏輯
    handleNotification(notification)

    // 通知不彈出
    //completionHandler([])

    // 在app內(nèi)彈通知
    completionHandler([.badge, .alert, .sound])
}

// app未打開(kāi)時(shí)調(diào)用
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userAction = response.actionIdentifier
    if userAction == UNNotificationDefaultActionIdentifier { 
        // 點(diǎn)擊通知欄本身
        log.debug("User opened the notification.")

        handleNotification(response.notification)

    } else if userAction == UNNotificationDismissActionIdentifier {
        // 通知dismiss,category創(chuàng)建時(shí)傳入U(xiǎn)NNotificationCategoryOptionCustomDismissAction才可以觸發(fā)
        log.debug("User dismissed the notification.")
    } else if userAction == "actionID" {
        // 自定義按鈕邏輯
    }

    completionHandler()
}

// iOS12新功能,在app系統(tǒng)通知設(shè)置里點(diǎn)擊按鈕跳到app內(nèi)通知設(shè)置的回調(diào)
public func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
    log.debug("Open notification in-app setting.")
}

擴(kuò)展閱讀

?著作權(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)容