0

I'm trying to download a file using Swift. This is the downloader class in my code:

class Downloader {
    class func load(URL: URL) {
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
    let request = NSMutableURLRequest(url: URL)
    request.httpMethod = "GET"
    let task = session.dataTask(with: URL)
    task.resume()
    }
}

I call the function like this:

if let URL = URL(string: "https://web4host.net/5MB.zip") {
        Downloader.load(URL: URL)
}

but this error message pops up:

2017-02-16 04:27:37.154780 WiFi Testing[78708:7989639] [] __nw_connection_get_connected_socket_block_invoke 2 Connection has no connected handler 2017-02-16 04:27:37.167092 WiFi Testing[78708:7989639] [] __nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler 2017-02-16 04:27:37.169050 WiFi Testing[78708:7989627] PAC stream failed with 2017-02-16 04:27:37.170688 WiFi Testing[78708:7989639] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNetwork: 2

Could someone tell me what I'm doing wrong and how I could fix it? Thanks!

Tony Tarng
  • 699
  • 2
  • 8
  • 17

1 Answers1

0

The code to receive the data is missing.

Either use delegate methods of URLSession or implement the dataTask method with the completion handler.

Further for a GET request you don't need an URLRequest – never use NSMutableURLRequest in Swift 3 anyway – , just pass the URL and don't use URL as a variable name, it's a struct in Swift 3

class Downloader {
    class func load(url: URL) { // better func load(from url: URL)
       let sessionConfig = URLSessionConfiguration.default
       let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
       let task = session.dataTask(with: url) { (data, response, error) in 
          // handle the error
          // process the data
       }
       task.resume()
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361