Swift - How to Set Cookie in Nsmutableurlrequest

Swift - How to set cookie in NSMutableURLRequest

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)

Create a cookie for NSURLRequest?

This is how you set properties in a cookie:

 NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
url, NSHTTPCookieOriginURL,
@"testCookies", NSHTTPCookieName,
@"1", NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];

In the example above:
url, testCookies, and 1 are the values. Likewise, NSHTTPCookieOriginURL, NSHTTPCookieName, NSHTTPCookieValue are the keys for the NSDictionary object, as in key-value pairs.

You set/get properties using NSDictionary and add to NSHTTPCookie.

how do i stop ios from automatically adding cookie to my NSMutableURLRequest


[request setHTTPShouldHandleCookies:NO];

NSMutableURLRequest setHTTPShouldHandleCookies

You should initialize the request with a URL; a request without a URL isn't a useful request. The default value for HTTPShouldHandleCookies is YES, so calling setHTTPShouldHandleCookies:YES should be unnecessary for a valid request. One has to conclude, then, that you don't have a valid request in the first place.

Swift NSURLSession NSURLRequest Cookies are not accepted

Issue is solved

In fact, cookies are accepted with the above code. I tried logging in to a different site and it worked. Also the login persisted. So why it did not work with my carrier's website?

Stupid me, my carrier has CSRF protection and other hidden form fields which I did not pay attention to. Hence, login did not work. Now I know how to fix it.

For anyone interested, I'll post my updated HttpClient.swift file which is a bit more tidy, I hope.

Please feel free to comment on my code and give me hints for improvement.

import Foundation

public class HttpClient {

private var session: NSURLSession
private var request: NSMutableURLRequest

public init(url: String) {
self.session = NSURLSession.sharedSession()
session.configuration.HTTPShouldSetCookies = true
session.configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.OnlyFromMainDocumentDomain
session.configuration.HTTPCookieStorage?.cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.OnlyFromMainDocumentDomain
self.request = NSMutableURLRequest(URL: NSURL(string: url)!)
}

public func send() -> String {
var ready = false
var content: String!

var task = session.dataTaskWithRequest(self.request) {
(data, response, error) -> Void in
content = NSString(data: data, encoding: NSASCIIStringEncoding) as! String
ready = true
}
task.resume()
while !ready {
usleep(10)
}
if content != nil {
return content
} else {
return ""
}
}

public func setUrl(url: String) -> HttpClient {
self.request.URL = NSURL(string: url)
return self
}

public func getMethod() -> String {
return self.request.HTTPMethod
}

public func setMethod(method: String) -> HttpClient {
self.request.HTTPMethod = method
return self
}

public func addFormData(data: Dictionary<String, String>) -> HttpClient {
var params: String = ""
var ctHeader: String? = self.request.valueForHTTPHeaderField("Content-Type")
let ctForm: String = "application/x-www-form-urlencoded"

if(data.count > 0) {
for(name, value) in data {
params += name + "=" + value + "&"
}

params = params.substringToIndex(params.endIndex.predecessor())
self.request.HTTPBody = params.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)

if ctHeader != nil {
self.request.setValue(ctForm, forHTTPHeaderField: "Content-Type")
}
}

return self
}

public func removeFormData() -> HttpClient {
self.request.setValue("text/html", forHTTPHeaderField: "Content-Type")
self.request.HTTPBody = "".dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)

return self
}
}

Is it possible to add values in an existing cookie in Objective C

Yes, you can add your own cookie with NSHTTPCookie and NSHTTPCookieStorage

1) Create dictionary to set properties of cookie like (below are few properties of cookie):


NSMutableDictionary *dictCookieID = [NSMutableDictionary dictionary];
[dictCookieID setObject:value forKey:NSHTTPCookieName];
[dictCookieID setObject:value forKey:NSHTTPCookieValue];
[dictCookieID setObject:value forKey:NSHTTPCookieDomain];
[dictCookieID setObject:value forKey:NSHTTPCookiePath];
[dictCookieID setObject:value forKey:NSHTTPCookieVersion];

2) Create a object of NSHTTPCookie


NSHTTPCookie *cookieID = [NSHTTPCookie dictCookieID];

3) Store cookie :


NSArray *cookies = [NSArray arrayWithObjects: cookieID,nil]; // You can add multiple cookies in this array
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieID];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

4) Load url to webview:


NSString* url = URL_NAME;
NSURL* nsUrl = [NSURL URLWithString:url];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:];
[request setHTTPShouldHandleCookies:YES];

NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[(NSMutableURLRequest *)request setAllHTTPHeaderFields:headers];

[webView loadRequest:request];


Related Topics



Leave a reply



Submit