34

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

func makeRequest(parameters: String, url:String){
    var postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
    var postLength:NSString = String(postData.length )
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var error:NSError?
    //request.HTTPBody = NSJSONSerialization.dataWithJSONObject(postData, options: nil, error: &error)
    request.HTTPBody = postData
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

        println("Response:\(response)")

        // Other stuff goes here

})

response is equal to:

<NSHTTPURLResponse: 0x7fcd205d0a00> { URL: http://XXX.XXX.XXX:0000/*** } { status code: 200, headers {
    "Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
    Connection = close;
    "Content-Length" = 16;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Mon, 13 Apr 2015 00:07:29 GMT";
    Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
    Pragma = "no-cache";
    Server = "Apache/2.2.15 (CentOS)";
    "Set-Cookie" = "MYCOOKIEIS=12dsada342fdshsve4lorewcwd234; path=/";
    "X-Powered-By" = "PHP/5.3.14 ZendServer/5.0";
} }

My problem here is that I don't know how to get the cookie that is there in "Set-Cookie" with name MYCOOKIEIS.

I'll use this when user Login so If user is not logged in -> Login (call login api) Else Go to home screen and call other APIs.

Somebody can help me to get the cookie out of there?

I found this answer but it is in Objective-C and I don't know how to do it with Swift

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Jorge Casariego
  • 21,948
  • 6
  • 90
  • 97

5 Answers5

51

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()
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 3
    Don't forget to delete cookies when you perform some sort of "logout". Check @Mellian response below – Aнгел Jul 28 '15 at 15:16
  • Remember that some cookies do not appear under the httpResponse.allHeaderFields. You will have to use the shared cookie store iOS provides instead. – JRam13 Jan 26 '17 at 19:33
  • I get it, but what if I want to set a cookie value , for example JSESSIONID, before running the task? – Josh Jun 15 '17 at 10:58
  • Saved My Week. Thanks a lot – YogiAR Jul 15 '20 at 22:27
16

Swift 3/4, concise solution:

let cookieName = "MYCOOKIE"
if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == cookieName }) {
    debugPrint("\(cookieName): \(cookie.value)")
}
zgorawski
  • 2,597
  • 4
  • 30
  • 43
15

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!)
}
Mellian
  • 151
  • 2
7

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)
Paul Cezanne
  • 8,629
  • 7
  • 59
  • 90
-1

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)")
    }
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143