Download File from Server Using Swift

How to download file in swift?

Example downloader class without Alamofire:

class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")

// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}

This is how to use it in your own code:

class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}

Swift 3 Version

Also note to download large files on disk instead instead in memory. see `downloadTask:

class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .get)

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("Success: \(statusCode)")
}

do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
completion()
} catch (let writeError) {
print("error writing file \(localUrl) : \(writeError)")
}

} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
}

Download file from server using Swift

edit/update: Xcode 11.5 • Swift 5.2

import UIKit
import AVFoundation

class ViewController: UIViewController {
var player: AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
let alarm = URL(string: "https://www.ringtonemobi.com/storage/upload/user_id_1/iphone-5-alarm-2016-08-21-01-49-25.mp3")!
do {
try alarm.download(to: .documentDirectory) { url, error in
guard let url = url else { return }
self.player = AVPlayer(url: url)
self.player.play()
}
} catch {
print(error)
}
}
}

import Foundation
extension URL {
func download(to directory: FileManager.SearchPathDirectory, using fileName: String? = nil, overwrite: Bool = false, completion: @escaping (URL?, Error?) -> Void) throws {
let directory = try FileManager.default.url(for: directory, in: .userDomainMask, appropriateFor: nil, create: true)
let destination: URL
if let fileName = fileName {
destination = directory
.appendingPathComponent(fileName)
.appendingPathExtension(self.pathExtension)
} else {
destination = directory
.appendingPathComponent(lastPathComponent)
}
if !overwrite, FileManager.default.fileExists(atPath: destination.path) {
completion(destination, nil)
return
}
URLSession.shared.downloadTask(with: self) { location, _, error in
guard let location = location else {
completion(nil, error)
return
}
do {
if overwrite, FileManager.default.fileExists(atPath: destination.path) {
try FileManager.default.removeItem(at: destination)
}
try FileManager.default.moveItem(at: location, to: destination)
completion(destination, nil)
} catch {
print(error)
}
}.resume()
}
}


Original answer

Xcode 8.3.2 • Swift 3.1

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
// create your document folder url
let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// your destination file url
let destination = documentsUrl.appendingPathComponent(audioUrl.lastPathComponent)
print(destination)
// check if it exists before downloading it
if FileManager.default.fileExists(atPath: destination.path) {
print("The file already exists at path")
} else {
// if the file doesn't exist
// just download the data from your url
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) in
// after downloading your data you need to save it to your destination url
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("audio"),
let location = location, error == nil
else { return }
do {
try FileManager.default.moveItem(at: location, to: destination)
print("file saved")
} catch {
print(error)
}
}).resume()
}
}

Download PDF and save to the Files in iPhone, not to the app data, Swift

Here's how to download any files and save to Photos(if image file) or Files (if pdf)

let urlString = "your file url"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Create URL to the source file you want to download
let fileURL = URL(string: urlString)
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)
do {
//Show UIActivityViewController to save the downloaded file
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
print("error: \(err)")
}
} 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()

Swift - Checking file sizes from a server before downloading is causing a lag in the app

The solution was to use a URL request and use the HTTP method "HEAD". Using the "expectedContentLength", you can find out the size of the file size and this causes no lag compared to the previous method mentioned.

func getFileSize(_ url: URL, completion: @escaping (Int64, Error?) -> Void){
let timeoutInterval = 5.0
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval)
request.httpMethod = "HEAD"

let group = DispatchGroup()
group.enter()

URLSession.shared.dataTask(with: request) { (data, response, error) in
let contentLength = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
completion(contentLength, error)
group.leave()
}.resume()
}

you can convert the size to MB using the code below if required

let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSizeInMB = countBytes.string(fromByteCount: Int64(ENTERYOURVALUEHERE))

How to display any extension file from server to your mobile in swift ios?

I use code like this to download a file and store it locally.

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(documentFilename)
return (fileURL, [.removePreviousFile])
}

Alamofire.download(url, to: destination).response { [unowned self] response in
// check download and call completion handler
}

What code did you use to download the file?

Swift from server to Use

If you are asking if it's possible to download a Swift file from a server, and run it on your iOS/iPadOS/watchOS/etc app, the answer is no. Even if you found a way, it would be rejected under rule 2.5.2 of the App Store Review Guidelines, which states:

Apps should be self-contained in their bundles, and may not read or
write data outside the designated container area, nor may they
download, install, or execute code which introduces or changes
features or functionality of the app, including other apps.

Educational apps designed to teach, develop, or allow students to test
executable code may, in limited circumstances, download code provided
that such code is not used for other purposes. Such apps must make the
source code provided by the Application completely viewable and
editable by the user.

Highlight mine.

How to download FTP file in swift 3

var url = URL(string: "ftp://user:password@host:port/path")
var data: Data? = nil
if let anUrl = url {
data = Data(contentsOf: anUrl)
}

then you will get the file into data

Note: I have simply converted this answer to Swift

How to download zip file from server in Swift?

I think that the question is a little broad, so consider this as a short and generic answer.

First:

  • You will need to download the archived file -you might want to use this method-.
  • After downloading the file, you should save it in a directory -let's say documents-.

Check this answer to know how you can achive those steps.

Second:

After getting the archived file, you will unarchive it -I suggest to use a third-party library for doing this, such as SSZipArchive-.

ALSO:

You could use Alamofire to handle the downloading proccess.

Hope this helped.



Related Topics



Leave a reply



Submit