iOS 10+ 移动推送,Swift,阿里云移动推送,iOS本地推送

扩展 AppDelegate, 在合适的地方调用

//
//  AppDelegate+Notification.swift
//
//  Created by Cy on 2019/12/11.
//  Copyright © 2019 ceeyang. All rights reserved.
//

import UIKit
import UserNotifications
import CloudPushSDK

/// APP 移动推送开发流程
/// ① APP 申请通知功能
/// ② 监听 APP 申请通知回调
/// ③ 通知权限申请成功  初始化第三方通知组件
/// ④ 讲申请通知权限成功后的 devicetoken 传到第三方
/// ⑤ 处理通知接受到的回调

// MARK: - Appdelegate Notification Extension
extension AppDelegate {
        
    /// 初始化阿里云移动推送组件
    func initCloudPush(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        
        /// 阿里云移动推送集成的时候会让你导入一个 plist 文件, 里面有阿里云推送所需数据 , 可以直接调用 autoInit 方法
        CloudPushSDK.autoInit { (result) in
            if result?.success == true {
                print("Init CloudPush Success, deviceId: \(String(describing: CloudPushSDK.getDeviceId()))")
            } else {
                print("Init CloudPush Failed, error: \(String(describing: result?.error))")
            }
        }
        
        CloudPushSDK.sendNotificationAck(launchOptions)
    }

    /// 阿里云移动推送绑定账号
    /// - Parameter account: 账号
    func bindAccount(account: String) {
        CloudPushSDK.bindAccount(account) { (result) in
            if result?.success == true {
                print("CloudPushSDK: bindAccount Success;")
            } else {
                print("CloudPushSDK: bindAccount Failed;\nerror: \(result?.error?.localizedDescription ?? "")")
            }
        }
    }
    
    /// 解绑账号
    func unbindAccount() {
        CloudPushSDK.unbindAccount { (result) in
            if result?.success == true {
                print("CloudPushSDK: bindAccount Success;")
            } else {
                print("CloudPushSDK: bindAccount Failed;\nerror: \(result?.error?.localizedDescription ?? "")")
            }
        }
    }
    
    /// 在合适的地方调用, 用于申请通知权限
    func registerNotification() {
        
        /// application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {}
        /// 上述方法中的 application === UIApplication.shared
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.getNotificationSettings { (settings) in
            
            /// 已经允许
            if settings.authorizationStatus == .authorized { return }
            
            /// 被拒绝
            if settings.authorizationStatus == .denied { return }
            
            /// 申请权限
            center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted: Bool, error: Error?) in
                DispatchQueue.main.async {
                    
                    if granted && error == nil {
                        /// 注册远程推送
                        UIApplication.shared.registerForRemoteNotifications()
                    } else {
                        print("RequestAuthorization Filed: Error\(error?.localizedDescription ?? "")")
                    }
                }
            }
        }

    }
        
    /// 申请通知权限成功
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        /// 苹果推送注册成功回调,将苹果返回的deviceToken上传到CloudPush服务器
        CloudPushSDK.registerDevice(deviceToken) { (result) in
            if result?.success == true {
                print("Register Device Success; DeviceToken:\(deviceToken.base64EncodedString())")
            } else {
                print("Register Device Failed;Error:\(result?.error?.localizedDescription ?? "")")
            }
        }
    }
    
    /// 申请通知权限失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // 注册失败后的结果, 可以在这里记录失败结果, 以后再伺机弹框给用户打开通知
        print("Register Notification Failed;Error:\(error.localizedDescription)")
    }
}

// MARK: - UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {

    /// APP 处于后台状态收到通知
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("didReceive response: \(response.notification.request.content.userInfo)")
        /// TODO: 接收到通知,处理业务逻辑
    }
    
    /// app 处于前台状态收到通知
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        /// let userInfo = notification.request.content.userInfo
        /// 自定义 APP 内通知, 省略代码   QQ的前台通知不走系统通知平台, APP 内震动+显示消息条数 后台通知走系统通知
        /// or
        /// 转发通知, 继续使用通知栏进行提示, 目测微信的APP内通知也是直接转发[APP 前台与后台 通知都是系统通知]
        completionHandler([.alert,.sound])
    }
}

extension UIApplication {

    /// 本地通知 调用方法如下
    ///
    /// UIApplication.localNotification(title: "title", subTitle: "subtitle",body: "body", badge:  1,userInfo: ["paramsId":"23333"])
    ///
    /// - Parameters:
    ///   - title: 标题
    ///   - subTitle: 副标题
    ///   - body: 内容
    ///   - badge: 角标数字, APP 右上角提示数字
    ///   - userInfo: 参数
    ///   - notificationTrigger: 通知类型, 详情请查阅 UNNotificationTrigger, 默认5 秒后发送通知不重复
    public static func localNotification(title: String?=nil,
                                         subTitle: String?=nil,
                                         body: String?=nil,
                                         badge: NSNumber?=nil,
                                         userInfo: [AnyHashable : Any]?=nil,
                                         notificationTrigger: UNNotificationTrigger?=nil) {
        var trigger = notificationTrigger
        
        if trigger == nil {
            trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        }
        
        // 2. 创建推送的内容 UNMutableNotificationContent
        let content = UNMutableNotificationContent()
        
        content.title    = title ?? ""
        content.subtitle = subTitle ?? ""
        content.body     = body ?? ""
        content.badge    = badge ?? 0
        content.sound    = UNNotificationSound.default
        content.userInfo = userInfo ?? [:]
        
        //    // 推送交互操作
        //    content.categoryIdentifier = @"Dely_locationCategory";
        //    [self addNotificationAction];
        
        // 3. 创建推送请求 UNNotificationRequest
        let request = UNNotificationRequest(identifier: "com.xakj.local.notification", content: content, trigger: trigger)
        
        // 4. 推送请求添加到推送管理中心 UNUserNotificationCenter
        let center = UNUserNotificationCenter.current()
        center.add(request, withCompletionHandler: { (error) in
            if error == nil {
                print("推送已添加成功")
            }
        })
    }
}

AppDelegate:


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    public static let shared = AppDelegate()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        /// 初始化通知,初始化其他通知组件
        initCloudPush(launchOptions)
        
        /// Other Code
        return true
    }
 }

在其他地方,准备提示申请权限的时候调用:

    AppDelegate.shared.registerNotification()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 223,858评论 6 521
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 95,753评论 3 402
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 170,876评论 0 366
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,560评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,574评论 6 399
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,097评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,477评论 3 427
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,452评论 0 278
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,980评论 1 324
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,017评论 3 343
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,168评论 1 354
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,807评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,497评论 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,976评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,094评论 1 275
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,659评论 3 380
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,196评论 2 363

推荐阅读更多精彩内容

  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 13,796评论 0 15
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,117评论 1 32
  • Hosai阅读 61评论 0 0
  • 前两天初中同学王斌问我念初一时是不是跟他同班,我说不记得了,他说你班主任是不是王克志老师,我说是。 一下子...
    華文2019阅读 852评论 2 9
  • 今天,处暑。 也是我的,阳历生日。 没有祝福,没有人知。 中午点了麻辣烫,杨国福。也许老板忘记放止泻药了,导致我和...
    安安文子阅读 157评论 0 0