Store and read the cookies from NSUserDefault

suggest change

This sample is Swift 2. synchronize is not required for NSUserDefaults to save. The defaults key is spelled customeWebsite in both methods.

import Foundation


class CookiesSingleton {

static let instance : CookiesSingleton = CookiesSingleton()
static var enableDebug = true

func loadCookies() {
    // saveCookies stores the property dictionaries under "customeWebsite".
    // The key is spelled that way in both methods.
    if let cookiesDetails = NSUserDefaults.standardUserDefaults().objectForKey("customeWebsite") as? [String: [String: AnyObject]] {
        for (_, cookieDict) in cookiesDetails {
            if let cookie = NSHTTPCookie(properties: cookieDict) {
                NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
                if CookiesSingleton.enableDebug {
                    print(cookieDict)
                }
            }
        }
    }
}

func  removeCookies(){
    NSURLCache.sharedURLCache().removeAllCachedResponses()
    NSURLCache.sharedURLCache().diskCapacity = 0
    NSURLCache.sharedURLCache().memoryCapacity = 0
    
    let storage : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    if let cookies = storage.cookies {
        for cookie in cookies {
            storage.deleteCookie(cookie as NSHTTPCookie)
        }
    }
    
    NSUserDefaults.standardUserDefaults().removeObjectForKey("customeWebsite")
    NSUserDefaults.standardUserDefaults().synchronize()
    
    if(CookiesSingleton.enableDebug){
        print("Cookies Removed")
    }
}

func saveCookies() {

    let cookieArray = NSMutableArray()
    let savedC = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies
    
    let allCookiesDic:NSMutableDictionary = NSMutableDictionary()

    for c : NSHTTPCookie in savedC! {

        let cookieProps = NSMutableDictionary()
        cookieArray.addObject(c.name)
        cookieProps.setValue(c.name, forKey: NSHTTPCookieName)
        cookieProps.setValue(c.value, forKey: NSHTTPCookieValue)
        cookieProps.setValue(c.domain, forKey: NSHTTPCookieDomain)
        cookieProps.setValue(c.path, forKey: NSHTTPCookiePath)
        cookieProps.setValue(c.version, forKey: NSHTTPCookieVersion)
        cookieProps.setValue(NSDate().dateByAddingTimeInterval(2629743), forKey: NSHTTPCookieExpires)

        allCookiesDic.setValue(cookieProps, forKey: c.name)

    }
    NSUserDefaults.standardUserDefaults().setValue(allCookiesDic, forKey: "customeWebsite")
    NSUserDefaults.standardUserDefaults().synchronize()
    
    if(CookiesSingleton.enableDebug){
        print("Cookies Saved")
    }
}

}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents