简体   繁体   中英

swift cookies urlsession request

I have a webapi in php which is work well. Now I want to use it in my app. Webapi use cookies to authenticate. So first time I create login task and save cookies from response.

save task:

function testLogin(){
 let loginUrlstring = ".../webapi/login.php"
 let passwordom = ""
 let emailem = ""

 guard let url = URL(string: loginUrlstring) else { return }

    let postString = "email=" + emailem + "&pw=" + passwordom

    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"
    urlRequest.httpShouldHandleCookies = true
    urlRequest.httpBody = postString.data(using: String.Encoding.utf8)     

    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest) { (data, response, error) in
        self.saveCookies(response: response)
        print("cookies mentve")
        print(response?.url)
    }
    task.resume()}

Now I want to use cookies and want to create request to get some data: data download task:

let probaUrl = "http://.../data.php"
let postString = "table=SomeTableName&key=someFieldID&value=20"
guard let url = URL(string: probaUrl) else { return }

loadCookies()
let cookiesArray = HTTPCookieStorage.shared.cookies
let headers = HTTPCookie.requestHeaderFields(with: cookiesArray!)


var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"//"POST"
urlRequest.httpShouldHandleCookies = true
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
urlRequest.allHTTPHeaderFields = headers

var session = URLSession(configuration: .default)
session.configuration.httpCookieAcceptPolicy = .always

session.configuration.httpAdditionalHeaders = headers
let task = session.dataTask(with: urlRequest) { (data, response, error) in
    print(response)
    print(data)
    if let data2 = data, let utf8Text = String(data: data2, encoding: .utf8) {
        print("Data: \(utf8Text)") // original server data as UTF8 string
    }
}
task.resume()

And it says: finished with error - code: -1001 print data--- nil Where is my mistake?

您应该打印碰巧的确切错误,以了解什么是错的。我的意思是let task = session.dataTask(with: urlRequest) { (data, response, error) in ... print(error) let task = session.dataTask(with: urlRequest) { (data, response, error) in ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM