ios - FCM 推送通知声音不起作用 IOS(可能重复但没有任何解决方案)
问题描述
推送通知显示并正常工作,但不会出现通知声音。当通知到来时,它只会振动。提到这里只有我能得到的数据和通知。我尝试使用自定义声音但失败了。这是我的有效载荷。
"content_available": true,
"priority": "high",
"data": {
"data": {
"title": "abc 2020-07-06 11:20:00",
"is_background": true,
"message": "2020-07-06 11:20:00",
"image": "",
"payload": {
"article_data": "",
"message_id": 21
},
"timestamp": "2020-07-08T13:20:00.041Z"
}
},
"apns": {
"headers": {
"apns-priority": "10"
},
"payload": {
"aps": {
"sound": "default"
}
}
},
"aps": {
"alert": {
"title": "abc 2020-07-06 11:20:00",
"subtitle": "2020-07-06 11:20:00",
"body": "2020-07-06 11:20:00",
"payload": {
"article_data": "",
"message_id": 21
}
},
"sound": "default"
},
"notification": {
"title": "abc 2020-07-06 11:20:00",
"body": "2020-07-06 11:20:00",
"content_available": true,
"click_action": "AboutAssociationActivity",
"icon": "",
"payload": {
"article_data": "",
"message_id": 21
},
"sound": "default"
}
}
这是我的 AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
static var badgeCount = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
UNUserNotificationCenter.current().delegate = self
if (launchOptions?[.remoteNotification] as? [String: AnyObject]) != nil {
print("Tariqul ")
}
FirebaseApp.configure()
application.registerForRemoteNotifications()
Messaging.messaging().`isAutoInitEnabled` = true
registerForPushNotifications()
guard AppSession.shared.isUserLoggedIn else {
let coordinator = LoginCoordinator(window: window!)
coordinator.start(from: window!)
return true
}
let coordinator = HomeViewControllerCoordinator()
coordinator.start(notifyData: nil, from: window!)
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("Tariqul willPresent \(userInfo)")
completionHandler([.alert, .sound, .badge])
// completionHandler([.alert])
}
/// Handle tap on the notification banner
///
/// - Parameters:
/// - center: Notification Center
/// - response: Notification response
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print("Tariqul didReceive UNUserNotificationCenter \(userInfo)")
let jsonString : [String : Any] = userInfo as! [String : Any]
do {
let d = jsonString["data"] as! String
let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
print("Tariqul didReceive UNUserNotificationCenter 2 \(res.payload.article_data)")
// displayNotifcation(message: res.message, title: res.title)
// configureNotification()
let coordinator = HomeViewControllerCoordinator()
// coordinator.notifyData = res
coordinator.start(notifyData: res, from: window!)
let content = UNMutableNotificationContent()
//Default sound
content.sound = UNNotificationSound.default
//Play custom sound
content.sound = UNNotificationSound.init(named:UNNotificationSoundName(rawValue: "pixies.wav"))
}
catch {
print(error)
}
// print("Tariqul notifyData \(jsonString)")
UIApplication.shared.applicationIconBadgeNumber = 1
print("notifyData \(extractUserInfo(userInfo: userInfo))")
// print("Tariqul didReceive \(userInfo)")
completionHandler()
}
func extractUserInfo(userInfo: [AnyHashable : Any]) -> String {
//var info = (title: "", body: "")
guard let aps = userInfo["aps"] as? [String: Any] else { return "info" }
guard let alert = aps["alert"] as? [String: Any] else { return "info" }
let body = alert["body"] as? String ?? ""
let subtitle = alert["subtitle"] as? String ?? ""
return "\(subtitle) \(body) "
}
func applicationWillResignActive(_ application: UIApplication) {
print("WillResignActive")
}
func applicationDidEnterBackground(_ application: UIApplication) {
print("DidEnterBackground")
}
func applicationWillEnterForeground(_ application: UIApplication) {
print("WillEnterForeground")
}
func applicationDidBecomeActive(_ application: UIApplication) {
print("DidBecomeActive")
}
func applicationWillTerminate(_ application: UIApplication) {
print("WillTerminate")
}
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
print("Tariqul \(remoteMessage.appData)")
}
}
extension AppDelegate {
func registerForPushNotifications() {
Messaging.messaging().delegate = self
// Messaging.messaging().shouldEstablishDirectChannel = true
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] (granted, error) in
print("Permission granted: \(granted)")
guard granted else {
print("Please enable \"Notifications\" from App Settings.")
self?.showPermissionAlert()
return
}
self?.getNotificationSettings()
}
} else {
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
@available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Tariqul Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken as Data
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Tariqul Device Token: \(token)")
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
guard !AppSession.shared.isUserLoggedIn else {
print("Tariqul Firebase registration token: \(fcmToken)")
let nextPageControl = NotificationTokenSetProtocol()
nextPageControl.setNotificationToken(FCMToken: fcmToken, completion: { (model, error) in
})
return
}
}
func displayNotifcation(message:String, title:String){
debugPrint("displaying notification : \(message)")
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: message, arguments: nil)
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: "requestid", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { (error) in
if error != nil{
debugPrint("error in showing notif \(error!.localizedDescription)")
}
debugPrint("displaying notification : success")
}
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Tariqul didReceive \(remoteMessage.messageID) \(remoteMessage.appData)")
do {
let d = remoteMessage.appData["data"] as! String
// let aps = remoteMessage.appData["aps"] as! String
let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
print("Tariqul didReceive res \(res.payload.article_data)")
// displayNotifcation(message: res.message, title: res.title)
// configureNotification()
//AppDelegate.badgeCount = +1
UIApplication.shared.applicationIconBadgeNumber = 1
}
catch {
print(error)
}
}
// didReceiveMessage
//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Tariqul error \(error)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Tariqul Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
do {
// UIApplication.shared.applicationIconBadgeNumber = 1
let jsonString : [String : Any] = userInfo as! [String : Any]
print("Tariqul didReceiveRemoteNotification \(jsonString)")
let d = userInfo["data"] as! String
let res = try JSONDecoder().decode(NotificationData.self,from:Data(d.utf8))
UIApplication.shared.applicationIconBadgeNumber = 1
}
catch {
print(error)
}
}
func showPermissionAlert() {
let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
self?.gotoAppSettings()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(settingsAction)
alert.addAction(cancelAction)
DispatchQueue.main.async {
// self.window?.rootViewController?.present(alert, animated: true, completion: nil)
guard AppSession.shared.isUserLoggedIn else {
let coordinator = LoginCoordinator(window: self.window!)
coordinator.start(from: self.window!)
return
}
}
}
private func gotoAppSettings() {
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.openURL(settingsUrl)
}
}
}
解决方案
推荐阅读
- reactjs - 导航器缺少导航道具。在 react-navigation 中,您必须直接设置您的应用容器
- vue.js - Nuxtjs 与 i18n-iso-country
- c++ - 二进制表达式 cout 问题的无效操作数
- java - Spring Security:谁将 AuthenticationManagerBuilder 传递给 WebSecurityConfigurerAdapter 配置方法?
- jquery - 点击时带href的跨度
- jquery - Django 数据表服务器端处理与 djang 模板引擎有问题
- python - 在 python 中查找 NLTK 模块
- python - Python GC 内存压缩
- node.js - 速率限制 - TCP 服务器 (net.Server)
- xcode - SCNView 导出的 Collada (.dae) 文件看起来不同,无法导入到 Blender