Firebaseを使ってリッチプッシュを送りたいと思っています。
テストプロジェクトでPHPからPUSH送信して受信までは出来ているのですが、
リッチプッシュの確認が出来ません。
下記を参考にNotificationService.swiftを作成したのですがうまくいきません。。。
Firebase Cloud Messagingで画像つきプッシュ通知を送信する
下記ソースですが、これでPUSH送信しても通常のPUSHが受信される状態です。
NotificationService.swiftとAppDelegate.swiftの挙動に関してそこまで詳しくないので、
何か足りないものがあるのかと思うのですが。。。
それともPHP側で送る内容に不備があるのか不明な状況です。。。
※PHPファイルに「mutable_content」と「image_url」が多いのは色々試していたためですm(_ _)m
NotificationService.swift
import UserNotifications class NotificationService: UNNotificationServiceExtension { let imageKey = AnyHashable("gcm.notification.image_url") var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // Modify the notification content here... bestAttemptContent.title = "(bestAttemptContent.title) [modified]" contentHandler(bestAttemptContent) } if let imageUrl = request.content.userInfo[imageKey] as? String { let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { [weak self] (data, response, error) in if let data = data { do { let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("push.png") try data.write(to: writePath) guard let wself = self else { return } if let bestAttemptContent = wself.bestAttemptContent { let attachment = try UNNotificationAttachment(identifier: "nnsnodnb_demo", url: writePath, options: nil) bestAttemptContent.attachments = [attachment] contentHandler(bestAttemptContent) } } catch let error as NSError { print(error.localizedDescription) guard let wself = self else { return } if let bestAttemptContent = wself.bestAttemptContent { contentHandler(bestAttemptContent) } } } else if let error = error { print(error.localizedDescription) } }) task.resume() } else { if let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } override func serviceExtensionTimeWillExpire() { modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
PHP側の処理
$api_key = 'APIKEY'; $base_url = "https://fcm.googleapis.com/fcm/send"; $title = 'test'; $body = 'body'; $token_key = 'TOKENKEY'; $data = array( "registration_ids" => $token_key ,"mutable_content" => True ,"priority" => "high" ,"notification" => array( "title" => $title ,"body" => $body ,"badge" => 1 ,"mutable_content" => True ,"image_url" => "画像URL" ) ,"data" => array( "title" => $title ,"body" => $body ,"badge" => 1 ,"image_url" => "画像URL" ,"mutable_content" => True ) ); $header = array( "Content-Type:application/json" ,"Authorization:key=".$api_key ); $context = stream_context_create(array( 'http' => array( 'method' => 'POST' ,'header' => implode("\r\n",$header) ,'content'=> json_encode($data) ) )); file_get_contents($base_url,false,$context);
AppDelegate.swift
import UIKit import UserNotifications import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let gcmMessageIDKey = "gcm.message_id" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) UIApplication.shared.registerForRemoteNotifications() } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: (messageID)") } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Unable to register for remote notifications: (error.localizedDescription)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: (messageID)") } completionHandler(UIBackgroundFetchResult.newData) } // ~~~~ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("APNs token retrieved: (deviceToken)") let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined() print("deviceToken!! = (token)") } } // [START ios_10_message_handling] @available(iOS 10, *) extension AppDelegate : UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: (messageID)") } // Print full message. print(userInfo) // Change this to your preferred presentation option completionHandler([]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: (messageID)") } // Print full message. print(userInfo) completionHandler() } } // [END ios_10_message_handling] extension AppDelegate : MessagingDelegate { // [START refresh_token] func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: (fcmToken)") // TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated. } // [END refresh_token] // [START ios_10_data_message] // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { print("Received data message: (remoteMessage.appData)") } // [END ios_10_data_message] }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/23 02:59
2018/06/25 10:58
2018/06/26 00:09
2018/07/03 02:00
2018/07/03 10:17 編集
2018/07/03 10:43