How to get cookie from a NSURLSession with Swift?

前端 未结 5 597
忘掉有多难
忘掉有多难 2020-12-13 10:04

I have a NSURLSession that calls dataTaskWithRequest in order to send a POST request in this way

func makeRequest(parameters: String, url:String){
    var po         


        
相关标签:
5条回答
  • 2020-12-13 10:46

    Swift 3/4, concise solution:

    let cookieName = "MYCOOKIE"
    if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == cookieName }) {
        debugPrint("\(cookieName): \(cookie.value)")
    }
    
    0 讨论(0)
  • 2020-12-13 10:58

    See the above answers but for Swift 3 you'll want something like this:

        var cookieProperties = [HTTPCookiePropertyKey:Any]()
    
        cookieProperties[HTTPCookiePropertyKey.name] = "foo"
        cookieProperties[HTTPCookiePropertyKey.value] = "bar"
        cookieProperties[HTTPCookiePropertyKey.path] = "baz"
        cookieProperties[HTTPCookiePropertyKey.domain] = ".example.com"
    
        let cookie = HTTPCookie(properties: cookieProperties)
    
    0 讨论(0)
  • 2020-12-13 11:01

    I had the same problem: This gets, sets or delete cookies:

    func showCookies() {
    
        let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        //println("policy: \(cookieStorage.cookieAcceptPolicy.rawValue)")
    
        let cookies = cookieStorage.cookies as! [NSHTTPCookie]
        println("Cookies.count: \(cookies.count)")
        for cookie in cookies {
            var cookieProperties = [String: AnyObject]()
    
            cookieProperties[NSHTTPCookieName] = cookie.name
            cookieProperties[NSHTTPCookieValue] = cookie.value
            cookieProperties[NSHTTPCookieDomain] = cookie.domain
            cookieProperties[NSHTTPCookiePath] = cookie.path
            cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
            cookieProperties[NSHTTPCookieExpires] = cookie.expiresDate
            cookieProperties[NSHTTPCookieSecure] = cookie.secure
    
            // Setting a Cookie
            if let newCookie = NSHTTPCookie(properties: cookieProperties) {
                // Made a copy of cookie (cookie can't be set)
                println("Newcookie: \(newCookie)")
                NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie)
            }
            println("ORGcookie: \(cookie)")
        }
    }
    
    func deleteCookies() {
    
        let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        let cookies = cookieStorage.cookies as! [NSHTTPCookie]
        println("Cookies.count: \(cookies.count)")
        for cookie in cookies {
            println("name: \(cookie.name) value: \(cookie.value)")
            NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie)
        }
    
        //Create newCookie: You need all properties, because else newCookie will be nil (propertie are then invalid)
        var cookieProperties = [String: AnyObject]()
        cookieProperties[NSHTTPCookieName] = "locale"
        cookieProperties[NSHTTPCookieValue] = "nl_NL"
        cookieProperties[NSHTTPCookieDomain] = "www.digitaallogboek.nl"
        cookieProperties[NSHTTPCookiePath] = "/"
        cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: 0)
        cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
        var newCookie = NSHTTPCookie(properties: cookieProperties)
        println("\(newCookie)")
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
    }
    
    0 讨论(0)
  • 2020-12-13 11:04

    Try this code:

    guard let realResponse = response as? HTTPURLResponse, realResponse.statusCode == 200 else {
        print("Not a 200 response")
        return
    }
    
    let fields = realResponse.allHeaderFields as? [String :String]
    
    if let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields!, for: response!.url!) {
        for cookie in cookies {
            print("name: \(cookie.name) value: \(cookie.value)")
        }
    }
    
    0 讨论(0)
  • 2020-12-13 11:06

    The Swift rendition might look something like:

    let task = session.dataTask(with: request) { data, response, error in
        guard
            let url = response?.url,
            let httpResponse = response as? HTTPURLResponse,
            let fields = httpResponse.allHeaderFields as? [String: String]
        else { return }
    
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
        HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
        for cookie in cookies {
            var cookieProperties = [HTTPCookiePropertyKey: Any]()
            cookieProperties[.name] = cookie.name
            cookieProperties[.value] = cookie.value
            cookieProperties[.domain] = cookie.domain
            cookieProperties[.path] = cookie.path
            cookieProperties[.version] = cookie.version
            cookieProperties[.expires] = Date().addingTimeInterval(31536000)
    
            let newCookie = HTTPCookie(properties: cookieProperties)
            HTTPCookieStorage.shared.setCookie(newCookie!)
    
            print("name: \(cookie.name) value: \(cookie.value)")
        }
    }
    task.resume()
    
    0 讨论(0)
提交回复
热议问题