如何在swift中的Alamofire Post请求中将令牌字符串(jwt)作为Cookie发送?

时间:2016-06-15 04:32:08

标签: ios swift cookies token alamofire

我想传递一个像jwt(json web token)这样的令牌,比如

  

?eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsb2NhbGhvc3QiLCJzdWIiOiIxIiwiZXhwIjoxNDY1ODA0NzY2LCJuYmYiOjE0NjU4MDM1NjYsImlhdCI6MTQ2NTgwMzU2NiwianRpIjoiaCtuUGxmZU5xZ2xEaW5WTW1iRUZRNEVFZEM3VFFKNFBRNzQrTkdUbVJCST0iLCJmaXJzdF9uYW1lIjoiR29sYW0iLCJsYXN0X25hbWUiOiJTYW1kYW5pIiwiZGV2aWNlX2NvdW50IjoiMSIsInBhY2tfaWQiOiIxIiwicGFja190YWciOiJSIiwic3RkYXRlIjoiMjAxNi0wNi0xMiAxMzowNTowNSIsImV4ZGF0ZSI6IjIwMTYtMDctMTIgMTM6MDU6MDUiLCJkaXNjb3VudCI6IjAuODAiLCJkYXlyZW0iOiIyOCIsImRhdGFyZW0iOiIxMDAiLCJtZXRob2QiOiJyZWd1bGFyIiwicmVmIjoib0pKTlorWVZnTVFheEw5RmpTV3l6TUJSSCtvcnJRMTZ1YVpnYTl5TWJEWXVjZEZSOVQyXC96OEhEYlVUQVlSSjVDWGdFaHptbHlNRXV1SEdxQWorSVNRPT0ifQ.vNLenIyy1bdLShrNZHx7mKfbvJmDKsMEEsk2EIHYis0

并且是String格式。我想在Alamofire POST请求中将此标记作为Cookie传递给API。请,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

您可以尝试在会话中设置HTTPCookieStorage。

Swift 2

let properties = [
    NSHTTPCookieDomain: "httpbin.org",
    NSHTTPCookiePath: "/post",
    NSHTTPCookieName: "foo",
    NSHTTPCookieValue: "bar",
]

let cookie = NSHTTPCookie(properties: properties)!
manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)

Swift 3

let properties = [
    HTTPCookiePropertyKey.domain: "httpbin.org",
    HTTPCookiePropertyKey.path: "/post",
    HTTPCookiePropertyKey.name: "foo",
    HTTPCookiePropertyKey.value: "bar",
]

let cookie = HTTPCookie(properties: properties)!
manager.session.configuration.httpCookieStorage?.setCookie(cookie)