22241

URL File Size With NSURLConnection - Swift

Question:

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 ?

Answer1:

The response parameter has the type

AutoreleasingUnsafeMutablePointer<NSURLResponse?>

which means that you can pass the address of an <em>optional</em> NSURLResponse as argument:

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

You can then conditionally cast the returned response to a NSHTTPURLResponse:

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

Note that you should check the return value of sendSynchronousRequest(), which is nil 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.

Answer2:

Swift 4 solution:

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) })

Recommend

  • How to run autogen.sh and swig on windows 7(SphinxPocket)
  • [OpenFileDialog-saveFileDialog error]The process cannot access the files because it is being used by
  • Behavioral to Structural Conversion Problems VHDL
  • Positioning buttons below menu bar with GridBagLayout
  • Libtool issue while compiling Liblinphone
  • Largest prime factor - euler project
  • Crc16 To String
  • App Engine OAuth2.0 authorized cron job to analyze Google Sheet
  • how to get text from in nested html elements using jericho?
  • How to load Images in Codeigniter?
  • django point definition
  • Why doesn't the GCC assembly output generate a .GLOBAL for printf
  • iOS any way to cancel all network requests
  • AFNetworking 3.0 Multipart form data for uploading image error
  • Google Text To Speech as a sperate class that can be called when ever needed?
  • Expand in the same as
  • Retrieve file size from web server
  • Prevent redirect response with Alamofire in Swift
  • Eclipse doesn't generate google cloud endpoint client library
  • MVC6 Cors - intercept preflight
  • Html.BeginRouteForm doesn't generate URL for named route
  • Error Domain=NSCocoaErrorDomain Code=3840 “Invalid value around character 0.” UserInfo={NSDebugDescr
  • How to access UIViewController's varaibles inside “func applicationWillResignActive”? Swift, iO
  • C++ std::set comparator
  • Ransack search string arrays stored in db
  • Get the negative of an Optional Chain
  • Uploading image with other parameters in SWIFT
  • No such module 'Parse' following Parse iOS Swift Quickstart guide
  • How to get the index of element in the List in c#
  • Less Conflicting Session Manager for Zope 2
  • How can we prepend rows to a react native list-view?
  • How to make Twilio api Post request with the help of AFNetworking?
  • What is the purpose of TaskExecutor in spring?
  • Moving mysql files across servers
  • swift auto completion not working in Xcode6-Beta
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Authorize attributes not working in MVC 4
  • EntityFramework adding new object to nested object collection