3

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

在以下代码中 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()

如果我使用初始化 cookie 存储,结果相同HTTPCookieStorage()

编辑

我尝试手动创建一个 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 作为饼干

4

2 回答 2

0

如果您打开头文件,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

为了拥有一个有效的应用程序组,您需要按照将应用程序添加到应用程序组中的说明进行添加

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

于 2018-04-02T00:41:19.607 回答
0

显然HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "groupName")似乎只适用于 iOS 10+,在 iOS 9 上即使文档说它也会返回 nil@available(iOS 9.0, *) open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage

您可以使用此解决方法:

let cookies: HTTPCookieStorage
    if #available(iOS 10.0, *) {
        cookies = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "groupName")
    } else {
        cookies = HTTPCookieStorage.shared
    }
于 2018-08-27T14:26:47.837 回答