在 ios swift 中的通知服务中播放流式处理 URL



我通过在磁盘中保存来在通知服务扩展中播放视频。现在,我想在通知服务扩展中将流式处理URL作为附件播放。我尝试直接将 URL 作为附件传递,但它在变量 attach1 中返回 nil。

下面是我的代码:

import UserNotifications
import UIKit
class 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)
        //Media
        func failEarly() {
            contentHandler(request.content)
        }
        guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
            return failEarly()
        }
        guard let attachmentURL = content.userInfo["attachment_url"] as? String, let url = URL(string: attachmentURL) else {
            return failEarly()
        }
        // Saving streaming url video
        var attach1 : UNNotificationAttachment?
        do {
        attach1 = try UNNotificationAttachment(identifier: request.content.categoryIdentifier, url: url, options: nil)
        } catch {
            failEarly()
        }    
        content.attachments = [attach1] as! [UNNotificationAttachment]
        contentHandler(content.copy() as! UNNotificationContent)
    }
    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)
        }
    }
}

我的流媒体网址来自Youtube。

任何帮助将不胜感激。

您必须了解一些方案。

  1. 如果您使用的是内容扩展名,则该时间category必须与UNNotificationContentExtension文件中Info.plist声明相同。
  2. UserNotificationAttachment不能存储数据网址,即它必须包含fileUrl,这是在UNNotificationServiceExtension中下载并在完成后返回的文件的网址。

因此,您的以下代码是完全错误的。

var attach1 : UNNotificationAttachment?
do {
    attach1 = try UNNotificationAttachment(identifier: request.content.categoryIdentifier, url: url, options: nil)
} catch {
    failEarly()
}    

我不确定,但是,youtube视频网址链接无法在AVPlayer播放,与AVPlayer一起使用时,应该需要网址中的视频扩展名。

正确检查所有内容。有关更多信息,请参阅 UNNotificationServiceExtension 和 UNNotificationContentExtension。

最新更新