Rich Push Notification - видео не воспроизводится в расширении содержимого уведомлений

Я работаю над богатыми уведомлениями Notification Content Extension и иметь возможность загружать images а также gif успешно, как следующий скриншот:

введите описание изображения здесь

Сейчас я пытаюсь воспроизвести видео и делаю следующий код для его воспроизведения.

- (void)didReceiveNotification:(UNNotification *)notification {
    //self.label.text = @"HELLO world";//notification.request.content.body;

    if(notification.request.content.attachments.count > 0)
    {

        UNNotificationAttachment *Attachen = notification.request.content.attachments.firstObject;


        NSLog(@"====url %@",Attachen.URL);
        AVAsset *asset = [AVAsset assetWithURL:Attachen.URL];
        AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];

        AVPlayer  *player = [AVPlayer playerWithPlayerItem:item];
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
        playerLayer.contentsGravity = AVLayerVideoGravityResizeAspect;
        player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

            [self.VideoPlayerView.layer addSublayer:playerLayer];
        [player play];
    }
}

В NSLog я также получаю URL файла видео. но это не сыграет. Пожалуйста, помогите, если у кого-то есть такое решение.

Благодарю.

3 ответа

Решение

Это очень маленькая ошибка, которую я сделал с кодом, который. мы должны проверить с startAccessingSecurityScopedResource если я делаю код, как следует

- (void)didReceiveNotification:(UNNotification *)notification {

    if(notification.request.content.attachments.count > 0)
    {
            UNNotificationAttachment *Attachen = notification.request.content.attachments.firstObject;

            if(Attachen.URL.startAccessingSecurityScopedResource)
            {

                NSLog(@"====url %@",Attachen.URL);
                AVAsset *asset = [AVAsset assetWithURL:Attachen.URL];
                AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];

                AVPlayer  *player = [AVPlayer playerWithPlayerItem:item];
                AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
                playerLayer.contentsGravity = AVLayerVideoGravityResizeAspect;
                player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
                playerLayer.frame = CGRectMake(0, 0, self.VideoPlayerView.frame.size.width, self.VideoPlayerView.frame.size.height);

                [self.VideoPlayerView.layer addSublayer:playerLayer];
                [player play];

            }                
        }
}

И видео играет. Boooom...

  1. Проверьте свой код. Убедитесь, что ресурс загружен на ваш диск.
  2. Если вы хотите воспроизвести URL-адрес, вы должны получить URL-адрес из уведомления userInfo и воспроизвести его в своем расширении контента

Чтобы ответить на вопрос, заданный в комментариях Анкура Пателя:

  1. Вы должны создать расширение содержимого уведомлений.
  2. - (void)didReceiveNotification:(UNNotification *)notificationтакое протокол UNNotificationContentExtension

Вот решение для воспроизведения видео в уведомлении в Swift 5.

      func didReceive(_ notification: UNNotification) {
    let content = notification.request.content
    titleLabel.text = content.title
    subtitleLabel.text = content.body
    
    playerController = AVPlayerViewController()
    preferredContentSize.height = 475
    
    // fetch your url string from notification payload.
    let urlString = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
    if let url = URL(string: urlString) {
        guard let playerController = self.playerController else { return }
        let player = AVPlayer(url: url)
        playerController.player = player
        playerController.view.frame = self.playerBackgroundView.bounds
        playerBackgroundView.addSubview(playerController.view)
        addChild(playerController)
        playerController.didMove(toParent: self)
        player.play()
    }
}

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

Другие вопросы по тегам