Swift NSURLSession NSURLRequest Cookies are not accepted

devnull

I'm new to swift and OS X programming. For my first steps I wanted to create a command line tool which logs me into the webinterface of my mobile carrier, and then shows the amount of my data left. I began to write a wrapper around NSURLSession to make things easier for me.

Problem: My program won't accept cookies.

I tried a lot of things, also setting cookie policies on the session object but nothing changed. How can I make my program accept cookies and how to use them in subsequent requests?

HttpClient.swift:

import Foundation

class HttpClient {

    private var url: NSURL!
    private var session: NSURLSession

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

    internal func sendGet() -> String {
        var ready = false
        var content: String!
        var request = NSMutableURLRequest(URL: self.url)

        var task = session.dataTaskWithRequest(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 ""
        }
    }

    internal func sendPost(params: String) -> String {
        var ready = false
        var content: String!
        var request = NSMutableURLRequest(URL: self.url)

        request.HTTPMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = params.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
        request.HTTPShouldHandleCookies = true

        var task = session.dataTaskWithRequest(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 ""
        }
    }

    internal func setUrl(url: String) {
        self.url = NSURL(string: url)
    }
}

main.swift

import Foundation

let loginPage = "https://service.winsim.de/"
let dataPage = "https://service.winsim.de/mytariff/invoice/showGprsDataUsage"

var hc = HttpClient(url: loginPage)
println(hc.sendPost("usernameField=username&passwordfield=password"))
hc.setUrl(dataPage)
println(hc.sendGet())
devnull

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
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swift NSURLSession NSURLRequest Cookies are not accepted

From Dev

Are cookies in UIWebView accepted?

From Dev

Set cookies with NSURLSession

From Dev

Set cookies with NSURLSession

From Dev

NSURLRequest setAllowsAnyHTTPSCertificate to Swift

From Dev

NSURLRequest issue with Swift

From Dev

Erase all cookies in NSURLSession iOS

From Dev

HTTP Headers w/ NSURLRequest in swift

From Dev

HTTP Request in Swift without NSURLRequest

From Dev

Scrapy CSRF cookies not accepted and results in a 302 Redirect

From Dev

Scrapy CSRF cookies not accepted and results in a 302 Redirect

From Dev

Swift - NSURLSession for Windows Authentication

From Dev

HTTP Request in Swift with NSURLSession

From Dev

Download a file with NSURLSession in Swift

From Dev

Swift Siesta and NSURLSession

From Dev

NSURLSession dataTaskWithRequest Swift

From Dev

Swift NSURLSession with NSURLSessionDelegate

From Dev

NSURLSession crashing from Swift

From Dev

How to convert NSURLRequest to NSMutableURLRequest in Swift 3?

From Dev

NSURLRequest swift getting fatal error exception

From Dev

Swift: Cannot convert type 'NSData!' to type 'NSURLRequest!'

From Dev

'NSURLRequest?' does not have a member named 'URL' - Swift

From Dev

How to convert NSURLRequest to NSMutableURLRequest in Swift 3?

From Dev

How to use NSURLSession and NSURLRequest to fetch users feeds and update in a tableview for a social networking iOS app?

From Dev

iOS certificate pinning with Swift and NSURLSession

From Dev

Problems with Watchkit Extension NSURLSession in Swift

From Dev

SWIFT: NSURLSession convert data to String

From Dev

NSURLSession Upload File To Server Swift

From Dev

what is the delegate of these NSURLSession methods in Swift?

Related Related

  1. 1

    Swift NSURLSession NSURLRequest Cookies are not accepted

  2. 2

    Are cookies in UIWebView accepted?

  3. 3

    Set cookies with NSURLSession

  4. 4

    Set cookies with NSURLSession

  5. 5

    NSURLRequest setAllowsAnyHTTPSCertificate to Swift

  6. 6

    NSURLRequest issue with Swift

  7. 7

    Erase all cookies in NSURLSession iOS

  8. 8

    HTTP Headers w/ NSURLRequest in swift

  9. 9

    HTTP Request in Swift without NSURLRequest

  10. 10

    Scrapy CSRF cookies not accepted and results in a 302 Redirect

  11. 11

    Scrapy CSRF cookies not accepted and results in a 302 Redirect

  12. 12

    Swift - NSURLSession for Windows Authentication

  13. 13

    HTTP Request in Swift with NSURLSession

  14. 14

    Download a file with NSURLSession in Swift

  15. 15

    Swift Siesta and NSURLSession

  16. 16

    NSURLSession dataTaskWithRequest Swift

  17. 17

    Swift NSURLSession with NSURLSessionDelegate

  18. 18

    NSURLSession crashing from Swift

  19. 19

    How to convert NSURLRequest to NSMutableURLRequest in Swift 3?

  20. 20

    NSURLRequest swift getting fatal error exception

  21. 21

    Swift: Cannot convert type 'NSData!' to type 'NSURLRequest!'

  22. 22

    'NSURLRequest?' does not have a member named 'URL' - Swift

  23. 23

    How to convert NSURLRequest to NSMutableURLRequest in Swift 3?

  24. 24

    How to use NSURLSession and NSURLRequest to fetch users feeds and update in a tableview for a social networking iOS app?

  25. 25

    iOS certificate pinning with Swift and NSURLSession

  26. 26

    Problems with Watchkit Extension NSURLSession in Swift

  27. 27

    SWIFT: NSURLSession convert data to String

  28. 28

    NSURLSession Upload File To Server Swift

  29. 29

    what is the delegate of these NSURLSession methods in Swift?

HotTag

Archive