Skip to content

Instantly share code, notes, and snippets.

@william8th
Created March 23, 2016 11:31
Show Gist options
  • Save william8th/33d8ae4e4f5c9576ff82 to your computer and use it in GitHub Desktop.
Save william8th/33d8ae4e4f5c9576ff82 to your computer and use it in GitHub Desktop.
Change cache control headers
//
// ViewController.swift
// CacheDelegate
//
// Created by Heng, William (Mobile Developer) on 23/03/2016.
// Copyright © 2016 Heng, William (Mobile Developer). All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "ANY URL THAT RETURNS JSON"
let myDelegate = MySessionDataDelegate(shouldChangeCache: true)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration() , delegate: myDelegate, delegateQueue: nil)
let url = NSURL(string: urlString)!
let request = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60)
for _ in 0...3 {
let dataTask = session.dataTaskWithRequest(request)
dataTask.resume()
sleep(1)
}
}
class MySessionDataDelegate : NSObject, NSURLSessionDataDelegate {
var shouldChangeCache = false
init(shouldChangeCache : Bool) {
self.shouldChangeCache = shouldChangeCache
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) {
var headerFields : [String : String] = (proposedResponse.response as! NSHTTPURLResponse).allHeaderFields as! [String : String]
var responseToCache : NSCachedURLResponse = proposedResponse
if (shouldChangeCache) {
let url = proposedResponse.response.URL!
let oldHTTPResponse = (proposedResponse.response as! NSHTTPURLResponse)
let statusCode = oldHTTPResponse.statusCode
headerFields["Cache-Control"] = "no-cache, max-age=0"
let HTTPVersion = "HTTP/1.1"
let newResponse = NSHTTPURLResponse(URL: url, statusCode: statusCode, HTTPVersion: HTTPVersion, headerFields: headerFields)
responseToCache = NSCachedURLResponse(response: newResponse!, data: proposedResponse.data)
}
print("header cache: \(headerFields["Cache-Control"])")
completionHandler(responseToCache)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
do {
let myData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print("received \(myData)")
} catch {
print("Cannot deserialise")
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
print("Error \(error)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment