web-dev-qa-db-ja.com

SwiftでNSURLSessionからCookieを取得する方法は?

この方法でPOSTリクエストを送信するためにdataTaskWithRequestを呼び出すNSURLSessionがあります

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

})

応答は次のとおりです。

<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";
} }

ここでの私の問題は、MYCOOKIEISという名前の「Set-Cookie」にあるCookieを取得する方法がわからないことです。

ユーザーがログインするときにこれを使用するので、ユーザーがログインしていない場合->ログイン(ログインAPIを呼び出す)または、ホーム画面に移動して他のAPIを呼び出します。

誰かがクッキーをそこから取り出すのを手伝ってくれる?

私はこれを見つけました answer しかしObjective-Cにあり、Swiftでそれを行う方法がわかりません

ありがとう!!

25
Jorge Casariego

Swiftレンディションは次のようになります。

let task = session.dataTaskWithRequest(request) { data, response, error in
    if let httpResponse = response as? NSHTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {
        let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: response!.URL!) 
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response!.URL!, mainDocumentURL: nil)
        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] = NSDate().dateByAddingTimeInterval(31536000)

            let newCookie = NSHTTPCookie(properties: cookieProperties)
            NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)

            print("name: \(cookie.name) value: \(cookie.value)")
        }
    }
}
task.resume()
42
Rob

私は同じ問題を抱えていました:これはクッキーを取得、設定、または削除します:

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!)
}
11
Mellian

Swift 3/4、簡潔なソリューション:

let cookieName = "MYCOOKIE"
if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == cookieName }) {
    debugPrint("\(cookieName): \(cookie.value)")
}
8
zgorawski

上記の回答を参照してください。ただし、Swift 3の場合、次のようなものが必要です。

    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)
7
Paul Cezanne