PHP-iOS push-уведомления с изображением - PullRequest
0 голосов
/ 15 марта 2019

Я пытаюсь отправить push-уведомление с изображением из моего веб-приложения в приложение iOS. Я получил уведомление со всем текстом и основным сообщением, которое я дал. Но данное изображение не отображается в уведомлении.

$url = 'https://fcm.googleapis.com/fcm/send';
$token = "*******************";
$title = "Title";
$body = "This is Test Notification";
$notification = array('title' =>$title , 'text' => $body, 'subtitle'=>'Sub title', 'sound' => 'default', 'badge' => '1', 'category' => 'CustomSamplePush', 'mutable-content'=>'1','urlImageString'=>'imageurl');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');

$fields = json_encode($arrayToSend);
echo $fields;
    $headers = array (
            'Authorization: key=' . "***********",
            'Content-Type: application/json',
            'authKey: keyhere',
            'authKeyId:****',
            'teamId: ****',
            'bundleId: *****',
            'endpoint: https://api.development.push.apple.com'
        );

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
    echo $result;
    curl_close ( $ch ); 

1 Ответ

0 голосов
/ 15 марта 2019

Для отображения мультимедийного содержимого, такого как изображения, аудио и видео, необходимо добавить NotificationServiceExtension в приложение для iOS.Для выполнения NotificationServiceExtension в приложении iOS необходимо отправить значение изменяемого содержимого как 1, что хорошо выглядит в упомянутой вами полезной нагрузке.В NotificationServiceExtension у вас будет около 10 секунд, чтобы загрузить изображение с URL-адреса, который вы отправляете в уведомлении.Как только изображение загружено, вам нужно сохранить изображение в FileManager.После этого вы инициализируете UNNotificationAttachment с URL-адресом изображения файла и передаете его обработчику завершения.Код PFA ниже

import UserNotifications

класс NotificationService: UNNotificationServiceExtension {

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...
        var urlString:String? = nil
        if let urlImageString = request.content.userInfo["urlImageString"] as? String {
            urlString = urlImageString
        }

        if urlString != nil, let fileUrl = URL(string: urlString!) {
            print("fileUrl: \(fileUrl)")

            guard let imageData = NSData(contentsOf: fileUrl) else {
                contentHandler(bestAttemptContent)
                return
            }
            guard let attachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "image.jpg", data: imageData, options: nil) else {
                print("error in UNNotificationAttachment.saveImageToDisk()")
                contentHandler(bestAttemptContent)
                return
            }

            bestAttemptContent.attachments = [ attachment ]
        }

        contentHandler(bestAttemptContent)
    }
}

override func serviceExtensionTimeWillExpire() {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
        contentHandler(bestAttemptContent)
    }
}

}

@ доступно (iOSApplicationExtension 10.0, *) расширение UNNotificationAttachment {

static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
    let fileManager = FileManager.default
    let folderName = ProcessInfo.processInfo.globallyUniqueString
    let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)

    do {
        try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil)
        let fileURL = folderURL?.appendingPathComponent(fileIdentifier)
        try data.write(to: fileURL!, options: [])
        let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
        return attachment
    } catch let error {
        print("error \(error)")
    }

    return nil
}

}

...