Save cookie persistence - swift

var url:NSURL=NSURL(string:"http://xxxxxxxx/index.php?s=/Public_verify.html")!
var data:NSData=NSData(contentsOfURL: url)!
var img:UIImage=UIImage(data:data)!
self.Verify.setBackgroundImage(img, forState: UIControlState.Normal)
var username=UserName.text
var password=PassWord.text
var verifycode=VerifyCode.text
let url=NSURL(string:"http://xxxxxxxx/index.php?s=/Public_doLogin.html")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let postString = "username=\(username)&password=\(password)&verifyCode=\(verifycode)&ajax=1"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
//cookie?
}
task.resume()
Code above, I used NSURLSession.sharedSession (). DataTaskWithRequest to POST login.
I quit APP, COOKIE disappears need to re-login
How to make cookie has been recorded, unless I log off the user?

Related

send urlrequest with same session id as webview

i have a WKWebView where users can login onto my server.
i also have a site that can be called from the background to renew the session time.
However, that request needs the same session cookie as my webview.
Since the cookies are handled by HTTPCookieStorage, my first attempt was to just send the request with
var request = URLRequest(url: URL(string: DOMAIN + PAGE_KEEP_ALIVE)!)
let task = URLSession.shared.dataTask(with: request)
task.resume()
But that didn't work(i can see the invalid time of all current sessions on my server).
So, i tried adding the cookies to the request:
let cookies = HTTPCookieStorage.shared.cookies(for: URL(string: DOMAIN)!)
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
var request = URLRequest(url: URL(string: DOMAIN + PAGE_KEEP_ALIVE)!)
request.allHTTPHeaderFields = headers
let task = URLSession.shared.dataTask(with: request)
task.resume()
but it still didn't work. Finally i tried request.httpShouldHandleCookies = true, but it still didn't help and i'm now out of ideas. Can anyone help me?
edit: after the comment from Larme the following worked
let store = webView.configuration.websiteDataStore.httpCookieStore
store.getAllCookies { cookies in
let domainCookies = cookies.filter { c in c.domain == DOMAIN }
let headers=HTTPCookie.requestHeaderFields(with: domainCookies)
var request = URLRequest(url: URL(string: DOMAIN + PAGE_KEEP_ALIVE)!)
request.allHTTPHeaderFields=headers
let task = URLSession.shared.webSocketTask(with: request)
task.resume()
}

How can I read the content of a form-data when the response is in html(Swift)

I'm building an iOS application and I need to access the information on a website. I've located the API endpoint, and was able to get a result in Postman
screenshot of API header and form data
So far I have this code which can allow me to make the request, but how do I parse the response(which is an HTML form, then display response in app
var urlRequest = URLRequest(url: url!)
urlRequest.setValue("application/form-data",forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
urlRequest.httpBody = postString.data(using: .utf8)
urlRequest = .init(url: url!)```
I actually found a great resources that showed how to send POST Request with post body, and how to read the response
How To send POST Request
Now it's just a matter of parsing the HTML that is returned, and displaying it in app.
let url = URL(string: Constants.rankingAPI)
guard let requestUrl = url else {
fatalError()
}
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString.htmlToString)")
}
}
task.resume()
}

Using facebook graph API to make HTTPS POST request in swift

When I use the url below normally on Google Chrome, I am able to create a new facebook test user, I get back a valid json with username and password, and other details back.
https://graph.facebook.com/v3.1/2232192233718728/accounts/test-users?installed=true&name=Thomasfsdks&locale=en_US&permissions=read_stream&method=post&access_token=2232192233718728|24q_TtCeh44Z0dUVm7x5pg2U5iQ
However, when I try to do it on swift, it does not seem to work correctly. I am unsure how to make it work.Below is the code in swift.
let appID = "2232192233718728"
let urlString = "https://graph.facebook.com/v3.1/" + appID + "/accounts/test-users?"
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let name = "Thomasdasfafada"
let accessToken = "2232192233718728|24q_TtCeh44Z0dUVm7x5pg2U5iQ"
let postString = "installed=true&name=" + name + "&locale=en_US&permissions=read_stream&method=post&access_token=" + accessToken
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
let responseString = String(data: data!, encoding: .utf8)
print("here"+"responseString = \(responseString)")
}
task.resume()

Set Cookies to HTTP POST Requests from Swift NSURLSession

I'm trying to use the below code but it doesn't work! Any Idea
let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieHeaderField = ["Cookie": self.CookieValue] // var CookieValue = String()
let url = URL
let parameters = ""
let postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: NSURL(string: url)!)
jar.setCookies(cookies, forURL: NSURL(string: url), mainDocumentURL: NSURL(string: url))
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
try this for setting cookies and for better usage understanding.
Below is the swift part for setting up cookie.
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(response.allHeaderFields as NSDictionary as! [String : String], forURL: response.URL!)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)

Swift - How to set cookie in NSMutableURLRequest

I'm trying to set cookie in my HTTP request
and I thought that below code would work:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("key=value;", forHTTPHeaderField: "Cookie")
but this code is not working.
does anyone have idea how to set it?
Updated answer for Swift 3
You want to look at HTTPCookieStorage.
// First
let jar = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url)
jar.setCookies(cookies, for: url, mainDocumentURL: url)
// Then
var request = URLRequest(url: url)
Original answer for swift 2
You want to look at NSHTTPCookieStorage.
// First
let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: url)
jar.setCookies(cookies, forURL: url, mainDocumentURL: url)
// Then
let request = NSMutableURLRequest(URL: url)
Swift 5
if let cookie = HTTPCookie(properties: [
.domain: ".my.domain.name.com",
.path: "/",
.name: "myCookieNameKey",
.value: "K324klj23KLJKH223423CookieValueDSFLJ234",
.secure: "FALSE",
.discard: "TRUE"
]) {
HTTPCookieStorage.shared.setCookie(cookie)
print("Cookie inserted: \(cookie)")
}
This may be useful for some one(Swift 5).
Avoid using NSMutableURLRequest in Swift. Instead follow the below snippet:
func request(with url: URL) -> URLRequest {
var request = URLRequest(url: url)
guard let cookies = HTTPCookieStorage.shared.cookies(for: url) else {
return request
}
request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies)
return request
}
Here is how it works in Swift 3.x after you set cookie using HTTPCookieStorage
let cookies=HTTPCookieStorage.shared.cookies(for: URL(string: cookieURL)!)
let headers=HTTPCookie.requestHeaderFields(with: cookies!)
let request = NSMutableURLRequest(url: requestURL!)
request.allHTTPHeaderFields=headers