Как создать баннер для push-уведомлений Apple с большим изображением - PullRequest
0 голосов
/ 13 февраля 2019

Как создать баннер уведомлений со значком приложения и большим изображением в iOS

Ответы [ 2 ]

0 голосов
/ 13 февраля 2019

Это называется "Richview Notification"

  • Вы можете просто превратить свои APNS в Richview, добавив ключи.

    "mutable-content": 1, "category:"richview"

  • Вы также можете запустить Local Richview для целей тестирования.

  • Вы должны добавить к цели для этого

1) Расширение содержимого уведомлений

2) Расширение службы

  • Вот подробные сведения о том, как это работает:

Прежде всего

import UserNotifications

Попросите пользователя разрешить push-уведомления

Вызовите это в вашем override func viewDidLoad() {

    requestPermissionsWithCompletionHandler { (granted) -> (Void) in

                DispatchQueue.main.async {
                    if granted {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                }
            }

Вот функция, которая запрашивает разрешение

private func requestPermissionsWithCompletionHandler(completion: ((Bool) -> (Void))? ) {

        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) {[weak self] (granted, error) in

            guard error == nil else {

                completion?(false)
                return
            }

            if granted {

                UNUserNotificationCenter.current().delegate = self
                self?.setNotificationCategories() // set your action categories

            }

            completion?(granted)
        }
    }

Вот как вы можете установить свои категории

    private func setNotificationCategories() {

              let btnAction = UNNotificationAction(identifier: "action", title: "Press", options: [])
        let textInput = UNTextInputNotificationAction(identifier: "comment", title: "Comment", options: [])

        let actionCategory =  UNNotificationCategory(identifier: "actionCategory", actions: [btnAction,textInput], intentIdentifiers: [], options: [])

UNUserNotificationCenter.current().setNotificationCategories([lactionCategory])

        }

Создать одну функцию, которая запускает локальное уведомление

func sendNotification() -> Void {

    notificationBodyField.resignFirstResponder()

    let content = UNMutableNotificationContent()
    content.title = "Local Notifications"
    content.subtitle =  "Subtitle"

    if  let characters = notificationBodyField.text?.characters, let text = notificationBodyField.text , characters.count > 0 {

        content.body = text
    }
    else {
        content.body = notificationBodyString
    }

    content.categoryIdentifier = "local"


    let url = Bundle.main.url(forResource: "gm", withExtension: "jpg")
    // download your image and provide local URL here 

    let attachment = try! UNNotificationAttachment(identifier: "image", url: url!, options: [:])

    content.attachments = [attachment]

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)

    let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) {[weak self] (error) in

        guard error == nil else {

            return
        }
    }

}

Вызвать эту функцию в вашем override func viewDidLoad() { после кода выше, и вы можетеНазовите это на любое действие, также это зависит от требования.

Для получения дополнительной информации, вы можете обратиться

https://developer.apple.com/documentation/usernotifications

http://thecodeninja.tumblr.com/post/125772843855/notifications-in-ios-9-quick-inline-reply-for

Надеюсь, это поможет вам:)

0 голосов
/ 13 февраля 2019

Настройка ОС

1.Создайте расширение службы уведомлений

В своем проекте вы должны создать расширение службы.Расширение сервиса позволяет модифицировать уведомление для включения мультимедиа.Чтобы добавить расширение службы уведомлений, нажмите Файл> Создать> Цель и выберите Расширение службы уведомлений.

enter image description here

2.Настройка расширения службы уведомлений

Поскольку расширение службы уведомлений имеет собственный идентификатор пакета, его необходимо настроить с использованием собственного идентификатора приложения и профиля обеспечения.Пожалуйста, проверьте это через Apple Developer Service.

3.Добавьте следующий код в расширение службы уведомлений

Хотя вы можете свободно реализовывать свой собственный метод в расширении службы уведомлений, вам необходимо убедиться, что ваш код правильно обрабатывает отправляемый носитель.с Leanplum.Ключ, связанный с мультимедиа в полезной нагрузке Leanplum: LP_URL.

Swift-код -

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        let imageKey = "LP_URL"
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        // MARK: - Leanplum Rich Push
        if let bestAttemptContent = bestAttemptContent {
            let userInfo = request.content.userInfo;

            // LP_URL is the key that is used from Leanplum to
            // send the image URL in the payload.
            //
            // If there is no LP_URL in the payload than
            // the code will still show the push notification.
            if userInfo[imageKey] == nil {
                contentHandler(bestAttemptContent);
                return;
            }

            // If there is an image in the payload,
            // download and display the image.
            if let attachmentMedia = userInfo[imageKey] as? String {
                let mediaUrl = URL(string: attachmentMedia)
                let LPSession = URLSession(configuration: .default)
                LPSession.downloadTask(with: mediaUrl!, completionHandler: { temporaryLocation, response, error in
                    if let err = error {
                        print("Leanplum: Error with downloading rich push: \(String(describing: err.localizedDescription))")
                        contentHandler(bestAttemptContent);
                        return;
                    }

                    let fileType = self.determineType(fileType: (response?.mimeType)!)
                    let fileName = temporaryLocation?.lastPathComponent.appending(fileType)

                    let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName!)

                    do {
                        try FileManager.default.moveItem(at: temporaryLocation!, to: temporaryDirectory)
                        let attachment = try UNNotificationAttachment(identifier: "", url: temporaryDirectory, options: nil)

                        bestAttemptContent.attachments = [attachment];
                        contentHandler(bestAttemptContent);
                        // The file should be removed automatically from temp
                        // Delete it manually if it is not
                        if FileManager.default.fileExists(atPath: temporaryDirectory.path) {
                            try FileManager.default.removeItem(at: temporaryDirectory)
                        }
                    } catch {
                        print("Leanplum: Error with the rich push attachment: \(error)")
                        contentHandler(bestAttemptContent);
                        return;
                    }
                }).resume()

            }
        }
    }

    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)
        }
    }

    // MARK: - Leanplum Rich Push
    func determineType(fileType: String) -> String {
        // Determines the file type of the attachment to append to URL.
        if fileType == "image/jpeg" {
            return ".jpg";
        }
        if fileType == "image/gif" {
            return ".gif";
        }
        if fileType == "image/png" {
            return ".png";
        } else {
            return ".tmp";
        }
    }

}

4.Обновление [didReceiveRemoteNotification Убедитесь, что обновили метод экземпляра приложения didReceiveRemoteNotification, чтобы он выполнял загрузку мультимедийного содержимого.Ниже приведен простой пример.

Swift -

func application(_ application: UIApplication,
                         didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        completionHandler(.newData)
}

5.Создайте расширенное push-уведомление с нашей панели инструментов После реализации приведенного выше кода вы можете свободно создавать расширенные push-уведомления с нашей панели мониторинга.Обязательно опробуйте его на зарегистрированном тестовом устройстве перед отправкой пользователям.

Set a dynamic image for Rich push messages (beta)

После включения бета-функции rich-push вы можете использовать синтаксис Jinja для установки изменяемого изображения-толчка.на основе значения параметра для инициированного push-уведомления.

Создание нового сообщения Push-уведомления.

Установите URL-адрес изображения, используя новый синтаксис Jinja, чтобы включить ваш параметр.

https://myimages.com/destinations/cities/{{parameter['dest_code']}}.jpg

enter image description here

Убедитесь, что вы используете скобки вокруг имени параметра (см. 'Dest_code' выше).

3.Вызовите push-уведомление о событии, параметр которого соответствует URL вашего изображения.

enter image description here

Событие Android с примером параметра:

HashMap<String, Object> paramsFlight = new HashMap<String, Object>();
paramsFlight.put("dest_code", "Varna");
Leanplum.track("flight_search", paramsFlight);

Событие iOS с примером параметра:

Leanplum.track("flight_search", withParameters: ["dest_code": "Varna"])
Протестируйте новое push-уведомление на реальном устройстве перед отправкой пользователям!

Примечания:

  1. Еслиизображение не существует, push будет отправлено без изображения.Изображение разрешается в приложении, поэтому push-уведомление все равно будет отправлено, но URL-адрес изображения не вернет изображение.

  2. Если параметр ("dest_code" в этом примере) равенне предоставлено в случае, push не будет отправлено.Если не указать правильный параметр в событии, произойдет сбой настройки Jinja, из-за которого не будет отправлено все сообщение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...