我有一个php webAPI,效果很好,我想在我的应用程序中使用它登录。我想用饼干。因此,当用户登录并且有效时,我会保存Cookie。当我只想在HTTPCookieStorage.shared中使用cookie时,我将它存储在userdefaults中。
我尝试将此用于我的新请求,我的问题是如何将Cookie添加到我的请求中?
我尝试了这个,但它不起作用......
let cookiesArray = HTTPCookieStorage.shared.cookies
print(cookiesArray)
//HTTPCookieStorage.shared.setCookies(cookiesArray!, for: url, mainDocumentURL: url)
let headers = HTTPCookie.requestHeaderFields(with: cookiesArray!)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpShouldHandleCookies = true
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
urlRequest.allHTTPHeaderFields = headers
//urlRequest.setValue("PHPSESSID=oe22uf92poc5c7s23u4ukl83g0", forHTTPHeaderField: "Cookie")
//URLSessionConfiguration().httpCookieAcceptPolicy = .always
let session = URLSession.shared
session.configuration.httpCookieStorage = HTTPCookieStorage.shared
session.configuration.httpCookieAcceptPolicy = .always
session.configuration.httpShouldSetCookies = true
session.configuration.httpAdditionalHeaders = headers
let task = session.dataTask(with: urlRequest) { (data, response, error) in
print(data)
print(response)
print(error)
print("itt az end\n")
}
task.resume()
答案 0 :(得分:1)
我还不能发表评论,但我同意需要更多信息。如果您收到错误,那么发布会有所帮助。另外,你得到的是
data
response
error
会有所帮助。
除此之外,我首先考虑将Charles设置为HTTP代理,这样您就可以确切地看到发出请求时发生了什么。了解您收到的回复会让您知道出了什么问题。