i am trying to get a file size from url before downloading
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];
and here is 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 error here
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)
'NSHTTPURLResponse' is not identical to 'NSURLResponse?'
did i miss something in swift here ?
The response parameter has the type
which means that you can pass the address of an optional
NSURLResponse
as argument:You can then conditionally cast the returned response to a
NSHTTPURLResponse
:Note that you should check the return value of
sendSynchronousRequest()
, which isnil
if no connection could be made.It is also recommended to call this method only from a separate thread (or use
sendAsynchronousRequest()
instead) because it can take a while to make a connection – in particular when using a cellular network – and the main thread would be blocked otherwise.Swift 4 solution: