• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - URLSession 在 iOS 上使用自定义 CookieStorage?

[复制链接]
菜鸟教程小白 发表于 2022-12-11 19:57:45 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我需要一个 urlsession 将 cookie 存储在单独的 cookieStorage 中

在下面的代码中urlSession中的cookieStorage和共享的cookieStorage是一样的,是否可以创建一个单独的cookie存储

    let config = URLSessionConfiguration.default
    session = URLSession(configuration: config)
    config.httpCookieAcceptPolicy = .always
    session.configuration.httpCookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "adfadf")

    let task = session.dataTask(with: URL(string: "https://www.google.com")!) { (data, response, error) in
        print((response as? HTTPURLResponse)?.allHeaderFields ?? "")

        DispatchQueue.main.async {
            print(self.session.configuration.httpCookieStorage?.cookies ?? "wtf")
            print(HTTPCookieStorage.shared === self.session.configuration.httpCookieStorage)
        }
    }

    task.resume()

如果我使用 HTTPCookieStorage()

初始化 cookie 存储,结果相同

编辑

我尝试手动创建一个 cookie 存储,并在请求完成后向其中添加 cookie

let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url)
 // cookies is not empty
self.cookieStore.setCookies(cookies, for: url, mainDocumentURL: nil)
print(self.cookieStore.cookies) //result is nil

最后我得到 nil 作为 cookie



Best Answer-推荐答案


如果您打开 NSHTTPCookieStorage 的头文件,您将看到此文档(由于某些原因,这些详细信息不会出现在常规文档中)。

/*!
    @method sharedCookieStorageForGroupContainerIdentifier:
    @abstract Get the cookie storage for the container associated with the specified application group identifier
    @param identifier The application group identifier
    @result A cookie storage with a persistent store in the application group container
    @discussion By default, applications and associated app extensions have different data containers, which means
    that the sharedHTTPCookieStorage singleton will refer to different persistent cookie stores in an application and
    any app extensions that it contains. This method allows clients to create a persistent cookie storage that can be
    shared among all applications and extensions with access to the same application group. Subsequent calls to this
    method with the same identifier will return the same cookie storage instance.
 */
@available(iOS 9.0, *)
open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage

为了拥有一个有效的应用组,您需要按照 Adding an App to an App Group 中的说明添加它.

我猜由于您没有将应用组添加到您的权利中,因此默认为 NSHTTPCookieStorage.shared

关于ios - URLSession 在 iOS 上使用自定义 CookieStorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593574/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap