Updated 12 December 2023
In today’s blog, we will learn how to Share and Download files from application in Swift.
Let’s create a sample project having an image and a download and share button to download and share the image.
Then create the download and share button outlet and let’s see the code for each of them.
A lot of developers want to be able to share their app data via email, Messages, or AirDrop. Sharing is a convenient way for users to send data to each other or between devices. It may even net you some new customers!
Here I have taken an image file that has to share.
Step 1: First initialize the image link.
1 |
let imgLink = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" |
Step 2: Then, create the outlet
1 2 3 4 5 6 7 8 9 10 11 |
@IBAction func shareClicked(_ sender: Any) { let objectsToShare = [link] as [Any] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList] activityVC.popoverPresentationController?.sourceView = self.shareBtn self.present(activityVC, animated: true, completion: nil) } |
Step 3: Now, when you click the share button the Share popup will appear.
Please check here to share the file code in objective C.
Now, let’s see the steps to download a file.
Step 1: First initialize the image link.
1 |
let imgLink = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" |
Step 2: Create downloadImage and getData functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
func downloadImage(from url: URL) { print("Download Started") getData(from: url) { data, response, error in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished") DispatchQueue.main.async { print("Image has been downloaded") if let image = UIImage(data: data) { //self.img = image UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } } } } |
1 2 3 |
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { URLSession.shared.dataTask(with: url, completionHandler: completion).resume() } |
Step 3: Finally call the downloadImage function from our outlet.
1 2 3 4 |
@IBAction func downloadCLicked(_ sender: Any) { let url = URL(string: imglink)! downloadImage(from: url) } |
Please check here if you want to download and view PDF in swift.
There are various ways to download the files from a URL but the best way to download it using Alamofire because it provides us various sub functionalities like:
a) downloadProgress : For showing the fraction completed while downloading the files.
b) validation : Allows to check the errors while downloading the files.
c) responseData: Contains the response for download.
Here is the code for using the Almofire for downloading from the URL :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
// MARK: - Load URL func downloadUsingAlamofire(url: URL, fileName: String) { let manager = Alamofire.SessionManager.default let destination: DownloadRequest.DownloadFileDestination = { _, _ in self.documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] self.documentsURL.appendPathComponent(fileName) print(self.documentsURL) return (self.documentsURL, [.removePreviousFile]) } manager.download(url, to: destination) .downloadProgress(queue: .main, closure: { (progress) in //progress closure print(progress.fractionCompleted) }) .validate { request, response, temporaryURL, destinationURL in // Custom evaluation closure now includes file URLs (allows you to parse out error messages if necessary) GlobalData.sharedInstance.dismissLoader() return .success } .responseData { response in if let destinationUrl = response.destinationURL as? URL { print(destinationUrl) if let statusCode = (response as? HTTPURLResponse)?.statusCode { print("Success: \(statusCode)") GlobalData.sharedInstance.dismissLoader() } let AC = UIAlertController(title:GlobalData.sharedInstance.language(key: "success"), message:GlobalData.sharedInstance.language(key: "filesavemessage"), preferredStyle: .alert) let okBtn = UIAlertAction(title: "view", style: .default, handler: {(_ action: UIAlertAction) -> Void in self.documentPathUrl = response.destinationURL //open file }) let noBtn = UIAlertAction(title: GlobalData.sharedInstance.language(key: "cancel"), style: .destructive, handler: {(_ action: UIAlertAction) -> Void in }) AC.addAction(okBtn) AC.addAction(noBtn) self.present(AC, animated: true, completion: { }) } else { GlobalData.sharedInstance.dismissLoader() } } } |
I hope this, will make you more comfortable using Alamofire functionality for downloading from the URL into your app. Thanks for tuning in once again!
Please follow the above steps to download and share the files in the application.
Thanks for reading 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.