Created
January 31, 2018 18:27
-
-
Save fethica/3ad09bcbc56ace668d9bb96ad15224a7 to your computer and use it in GitHub Desktop.
[Swift] Get the size (ContentLength) of an http remote file
This file contains hidden or 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 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