Skip to content

Instantly share code, notes, and snippets.

@fethica
Created January 31, 2018 18:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fethica/3ad09bcbc56ace668d9bb96ad15224a7 to your computer and use it in GitHub Desktop.
Save fethica/3ad09bcbc56ace668d9bb96ad15224a7 to your computer and use it in GitHub Desktop.
[Swift] Get the size (ContentLength) of an http remote file
func fetchContentLength(for url: URL, completionHandler: @escaping (_ contentLength: UInt64?) -> ()) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil,
let response = response as? HTTPURLResponse,
let contentLength = response.allHeaderFields["Content-Length"] as? String else {
completionHandler(nil)
return
}
completionHandler(UInt64(contentLength))
}
task.resume()
}
let url = URL(string: "https://s3.amazonaws.com/x265.org/video/Tears_400_x265.mp4")!
fetchContentLength(for: url, completionHandler: { (contentLength) in
print(contentLength ?? 0)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment