Download File From a Remote URL in Swift.

With this short 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 or a large size.

  • 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 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 as URL!
    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()
    
  }

}


Checkout more Swift code examples at Swift Code Examples page.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon