新消息通知

前言:App中的新消息通知一般都长这个样子的

在这里插入图片描述
里面涉及到了几个点,在这里记录一下

  • 一:要遵循UNUserNotificationCenterDelegate代理,获取用户当前状态
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
        
    let center = UNUserNotificationCenter.current()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        center.delegate = self
        center.getNotificationSettings { (notificationSettings) in
            DispatchQueue.main.async {
                switch notificationSettings.authorizationStatus {
                    case .notDetermined://用户尚未决定应用程序是否可以发布用户通知。
                        self.openAuthorization()
                    case .denied://应用程序没有被授权发布用户通知。
                        print("未开启")
                    case .authorized://应用程序被授权发布用户通知。
                        print("已开启")
                    case .provisional://应用程序被授权发布非中断用户通知。
                        break
                    default:
                        break
                }
            }
        }
    }
}
  • 二:如果用户尚未授权,我们需要弹出系统的弹出,提醒用户授权(这个一般在进入APP就弹出了)

在这里插入图片描述
代码:

//用户尚未授权
func openAuthorization() {
    self.center.requestAuthorization(options: [.badge, .sound, .alert, .carPlay ]) { (flag, error) in
        DispatchQueue.main.async {
            if flag == true {
                print("已开启")
            }else{
                print("未开启")
            }
        }
    }
}
  • 三:如果我们想要用户APP内直接跳转设置
//打开设置
func openSystemSettings() {
    let urlObj = URL(string: UIApplication.openSettingsURLString)
    // 前往设置
    UIApplication.shared.open(urlObj! as URL, options: [ : ]) { (flag) in
        if flag == true {
            /// 回调 "已开启"
        }else{
            /// 回调 "未开启"
        }
    }
}
  • 四:在需要提示音的地方播放系统的声音或振动(这里的开关我用的UserDefaults)
func playSystemSound() {
    /// 震动开启
    if UserDefaults.standard.object(forKey: "SystemVibrate") as? Bool != false {
        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
    }
    
    /// 声音开启
    if UserDefaults.standard.object(forKey: "SystemSound") as? Bool != false {
         var soundID:SystemSoundID = 0;
         let path = "/System/Library/Audio/UISounds/sms-received1.caf"
         let filePath = NSURL.fileURL(withPath: path, isDirectory: false)
         AudioServicesCreateSystemSoundID(filePath as CFURL, &soundID)
         AudioServicesPlaySystemSound(soundID)
    }
}

总结:以上就是我对新消息通知记录的几个小的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值