Wanted to find size of a file on some server before downloading it in iOS 7... I have a method of NSURLConnectionDelegate but it is deprecated after iOS 4.3
Here was
Also using URlSession
you can get the file size like this without downloading actual data:
func getPdfSize(for url: URL) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { [weak self] (_, response, _) in
if let response = response {
let size = response.expectedContentLength
DispatchQueue.main.async {
self?.fileSizeLabel.text = ByteCountFormatter.string(fromByteCount: size, countStyle: .file)
}
}
}.resume()
}
Notice also you can use the native iOS ByteCountFormatter
to format the byte count into a readable string.
Code in Swift 5