Last active
March 3, 2022 01:45
-
-
Save perlmunger/b47b7c49240c48f562b8 to your computer and use it in GitHub Desktop.
Swift NSURLSession Check File Last Modified Date With HEAD Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func checkShouldDownloadFileAtLocation(urlString:String, completion:((shouldDownload:Bool) -> ())?) { | |
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!) | |
request.HTTPMethod = "HEAD" | |
var session = NSURLSession.sharedSession() | |
var err: NSError? | |
var task = session.dataTaskWithRequest(request, completionHandler: { [weak self] data, response, error -> Void in | |
if let strongSelf = self { | |
var isModified = false | |
var err: NSError? | |
if let httpResp: NSHTTPURLResponse = response as? NSHTTPURLResponse { | |
let lastModifiedDate = httpResp.allHeaderFields["Last-Modified"] as? String | |
if lastModifiedDate != nil { | |
let newLastModifiedDate = strongSelf.dateFormatter.dateFromString(lastModifiedDate!) | |
if newLastModifiedDate != nil { | |
let currentLastModifiedDate = NSUserDefaults.standardUserDefaults().objectForKey("LastModifiedDate") as? NSDate | |
if currentLastModifiedDate == nil { | |
isModified = true | |
} else { | |
isModified = !newLastModifiedDate!.isEqual(currentLastModifiedDate!) | |
} | |
NSUserDefaults.standardUserDefaults().setObject(newLastModifiedDate!, forKey: "LastModifiedDate") | |
NSUserDefaults.standardUserDefaults().synchronize() | |
} | |
} | |
} | |
if completion != nil { | |
dispatch_async(dispatch_get_main_queue(), { () -> Void in | |
completion!(shouldDownload: isModified) | |
}) | |
} | |
} | |
}) | |
task.resume() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.checkShouldDownloadFileAtLocation("http://urltolocation.com/of/file.jpg", completion: { (shouldDownload) -> () in | |
if shouldDownload { | |
// Go download the file now | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this