Download File From a Remote URL in Swift.

With this short Swift code example, I am going to share with you how to download a large file from a remote URL. It could be an image file, video file, or even a ZIP archive of a large size.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

The Swift code example below will cover the following:

  • Create a destination URL,
  • Create URL to the source file you want to download,
  • Use URLSession to download a file from a remote URL,
  • Copy downloaded file from a temporary URL to a destination URL on the device,
  • Handle file download SUCCESS and ERROR situations.

Download File From a Remote URL. Code Example in Swift 3.

import UIKit
class ViewController: UIViewController  {
override func viewDidLoad() {
    super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    // Create destination URL 
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
    
    //Create URL to the source file you want to download
    let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")
    
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
 
    let request = URLRequest(url:fileURL!)
    
    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }
            
            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }
            
        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
        }
    }
    task.resume()
    
  }
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *