Search code examples
iosswiftnsurlconnectionnsurlnshttpurlresponse

Getting file size with NSURLConnection is very slow


I try to get the filesize of a file stored on a server.

I manage to do, but it takes as long as I would download it.

I assume it will download the file to evaluate the size.

Is there a faster way to get the file size?

func getFileSizeFromURL(sURL:String) -> String{

    let urlPath: String = sURL;
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)


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


    var size:String="";

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


        size="\(httpResponse.expectedContentLength)"

    }

    return size;

}

Solution

  • I assume it will download the file to evaluate the size.

    Yes, that's because you actually are downloading the file. You should instead use a HEAD request to get just the data about the file. Changing the method from GET or POST to HEAD will get you just the HTTP headers. Insert a line like this after you create request1:

    request1.HTTPMethod = "HEAD"