URL file size with NSURLConnection - Swift

I'm trying to get file size from url before upload

here is the obj-c code

    NSURL *URL = [NSURL URLWithString:"ExampleURL"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
    long long size = [response expectedContentLength];

but Swift Code

var url:NSURL = NSURL(string: "ExmapleURL")
                var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
                request.HTTPMethod = "HEAD"
                var response = NSHTTPURLResponse()
                NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

but i have a mistake here

NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

'NSHTTPURLResponse' is not identical to 'NSURLResponse?'

did i miss something here fast?

+1
source share
2 answers

The response parameter is of type

AutoreleasingUnsafeMutablePointer<NSURLResponse?>

which means you can pass the address of an optional argument NSURLResponseas an argument:

var response : NSURLResponse?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)

Then you can conditionally discard the returned answer to NSHTTPURLResponse:

if let httpResponse = response as? NSHTTPURLResponse {
    println(httpResponse.expectedContentLength)
}

Please note that you must check the return value sendSynchronousRequest(), which nilif the connection cannot be completed.

( sendAsynchronousRequest()) - , - .

+3

Swift 4:

func fetchContentLength(for url: URL, completionHandler: @escaping (_ contentLength: Int64?) -> ()) {

    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(Int64(contentLength))
    }

        task.resume()
}

// Usage:

let url = URL(string: "https://s3.amazonaws.com/x265.org/video/Tears_400_x265.mp4")!

fetchContentLength(for: url, completionHandler: { contentLength in
    print(contentLength ?? 0)
})
0

Source: https://habr.com/ru/post/1017045/


All Articles