Swift - How to set cookie in NSMutableURLRequest

后端 未结 4 858
南笙
南笙 2020-12-30 08:01

I\'m trying to set cookie in my HTTP request and I thought that below code would work:

let request  = NSMutableURLRequest(URL: url)
request.HTTPMethod = \"GE         


        
相关标签:
4条回答
  • 2020-12-30 08:12

    This may be useful for some one(Swift 5). Avoid using NSMutableURLRequest in Swift. Instead follow the below snippet:

    func request(with url: URL) -> URLRequest {
        var request = URLRequest(url: url)
    
        guard let cookies = HTTPCookieStorage.shared.cookies(for: url) else {
            return request
        }
    
        request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies)
        return request
    }
    
    0 讨论(0)
  • 2020-12-30 08:28

    Swift 5

    if let cookie = HTTPCookie(properties: [
        .domain: ".my.domain.name.com",
        .path: "/",
        .name: "myCookieNameKey",
        .value: "K324klj23KLJKH223423CookieValueDSFLJ234",
        .secure: "FALSE",
        .discard: "TRUE"
    ]) {
        HTTPCookieStorage.shared.setCookie(cookie)
        print("Cookie inserted: \(cookie)")
    }
    
    0 讨论(0)
  • 2020-12-30 08:33

    Updated answer for Swift 3

    You want to look at HTTPCookieStorage.

    // First
    let jar = HTTPCookieStorage.shared
    let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
    let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url)
    jar.setCookies(cookies, for: url, mainDocumentURL: url)
    
    // Then
    var request = URLRequest(url: url)
    

    Original answer for swift 2

    You want to look at NSHTTPCookieStorage.

    // First
    let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
    let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: url)
    jar.setCookies(cookies, forURL: url, mainDocumentURL: url)
    
    // Then
    let request  = NSMutableURLRequest(URL: url)
    
    0 讨论(0)
  • 2020-12-30 08:36

    Here is how it works in Swift 3.x after you set cookie using HTTPCookieStorage

    let cookies=HTTPCookieStorage.shared.cookies(for: URL(string: cookieURL)!)
    let headers=HTTPCookie.requestHeaderFields(with: cookies!)
    let request  = NSMutableURLRequest(url: requestURL!)
    request.allHTTPHeaderFields=headers
    
    0 讨论(0)
提交回复
热议问题