programing

NSURLSession에서 Swift를 사용하여 쿠키를 가져오려면 어떻게 해야 합니까?

showcode 2023. 3. 11. 09:41
반응형

NSURLSession에서 Swift를 사용하여 쿠키를 가져오려면 어떻게 해야 합니까?

이 방법으로 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"에 있는 쿠키를 어떻게 구해야 하는지 모른다는 것입니다.

사용자가 로그인 할 때 사용합니다.-> 로그인하지 않은 경우 -> 로그인(call login api) 그렇지 않으면 홈 화면으로 이동하여 다른 API를 호출합니다.

누가 쿠키 꺼내는 것 좀 도와줄래?

을 찾았는데 Objective-C에 있고 Swift로 어떻게 하는지 모르겠어요.

Swift 버전은 다음과 같습니다.

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()

저도 같은 문제가 있었습니다.쿠키 가져오기, 설정 또는 삭제:

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

신속한 3/4 간결한 솔루션:

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

위의 답변을 참조해 주십시오.단, 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)

다음 코드를 사용해 보십시오.

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

언급URL : https://stackoverflow.com/questions/29596206/how-to-get-cookie-from-a-nsurlsession-with-swift

반응형