【问题标题】:How to set correct cookies Value against AVURLAssetHTTPCookiesKey while initialising AVURLAsset如何在初始化 AVURLAsset 时针对 AVURLAssetHTTPCookiesKey 设置正确的 cookie 值
【发布时间】:2020-03-11 06:56:53
【问题描述】:

我必须播放 HLS 流并且它是安全/受保护的。为了下载清单文件和进一步的 ts 文件,预计请求会发送有效的 Cookie 信息。我确实从服务器接收到 Cookie 信息,但它不是响应标头的一部分,而是作为响应字符串的一部分。这意味着 Cookies 不会自动成为 NSHTTPSStorage 的一部分,应用程序必须使用响应字符串并从那里获取 Cookies 信息;在初始化 AVURLAsset 时需要进一步设置。根据 AVURLAsst 文档,为了发送 Cookie 信息,我们应该使用选项“AVURLAssetHTTPCookiesKey”。我在下面的代码中提到了如何使用这个键来初始化 AVURLAsset

    let cookieOptions = [AVURLAssetHTTPCookiesKey: Any]
    let assets = AVURLAsset(url: url as URL, options: cookieArrayOptions)

我的主要问题是如何针对 AVURLAssetHTTPCookiesKey 设置值。它采用 'Any' 类型的值。由于 Apple 只是提到它期望 Any 值,并没有说明它在内部如何解释并以正确格式转换该值。

我尝试了两种设置值的方法:假设我必须设置两个 Cookie 键,即 MyCookies1、MyCookies2

使用 NSHTTPSStorage 的方法 1

let propertiesKey1 = [HTTPCookiePropertyKey.domain : "Domain=abc.com",HTTPCookiePropertyKey.path:"/",HTTPCookiePropertyKey.secure:true,HTTPCookiePropertyKey.init("HttpOnly"):true,HTTPCookiePropertyKey.value:"abc1",HTTPCookiePropertyKey.name:"MyCookies1"] as [HTTPCookiePropertyKey : Any]
let propertiesKey2 = [HTTPCookiePropertyKey.domain : "Domain=abc.com",HTTPCookiePropertyKey.path:"/",HTTPCookiePropertyKey.secure:true,HTTPCookiePropertyKey.init("HttpOnly"):true,HTTPCookiePropertyKey.value:"abc2",HTTPCookiePropertyKey.name:"MyCookies2"] as [HTTPCookiePropertyKey : Any]
let cookieKey1 =   HTTPCookie(properties: propertiesKey1)
let cookieKey2 =   HTTPCookie(properties: propertiesKey2)
HTTPCookieStorage.shared.setCookie(cookieKey1!)
HTTPCookieStorage.shared.setCookie(cookieKey2!)
let cookiesArray = HTTPCookieStorage.shared.cookies!
let cookieArrayOptions = [AVURLAssetHTTPCookiesKey: cookiesArray]
guard let url = URL(string:"abc.com") else { return }
let assets = AVURLAsset(url: url as URL, options: cookieArrayOptions)

但这不起作用,AVPlayer 刚刚初始化并停止工作

方法2

 let values = ["Cookie": "MyCookies1=abc1; MyCookies2=abc2"]
 let cookieArrayOptions = [AVURLAssetHTTPCookiesKey: values]
 guard let url = URL(string:"abc.com") else { return }
 let assets = AVURLAsset(url: url as URL, options: cookieArrayOptions)

但是这个选项总是崩溃。可能是我没有以正确的格式设置值。

我已尽力提供尽可能多的信息,但如果您需要任何进一步的信息,请告诉我。

【问题讨论】:

    标签: ios avplayer avurlasset


    【解决方案1】:

    经过几次尝试,我能够使用方法 1 使用 NSHTTPSStorage。我犯了一个错误,没有使用 HTTPS 流 URL。我已经允许通过 ATS 播放非 HTTP url 并允许任意加载。但 AVURLAssetHTTPCookiesKey 只希望为 cookie 提供 HTTPS url。我使用了 HTTPS 流,最终在播放 HLS 流时下载清单/段文件时,Cookie 开始在请求标头内部发送

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多