Download the Data from URL
Some time we need to download the data from URL like PDF file, word file , CSV file etc. Most of server required the parameter in header so we need to provide the data through header after that he will provide the final url to download,
If the all required value passes correctly then it will automatically downloaded to your provided file path.
Here I have used Local file directory where we are storing all this files.
Steps:
1: We need to declare the request URL & File name:
like that: here i am downloading .pdf file
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 |
var fileName:String = "" let date = Date() let formatter = DateFormatter() formatter.dateFormat = "dd.MM.yyyy" let storeId = defaults.object(forKey: "storeId") var url:String = "" if currentdownload == "invoice"{ url = HOST_NAME+API; fileName = "invoice"+formatter.string(from: date)+".pdf" }else{ url = HOST_NAME+"mobikulmphttp/marketplace/downloadAllShipping"; fileName = "shipping"+formatter.string(from: date)+".pdf" } let post = NSMutableString(); post .appendFormat("storeId=%@&", storeId as! CVarArg); post .appendFormat("dateTo=%@&", untillDateTextField.text! as CVarArg); post .appendFormat("dateFrom=%@&", fromDateTextField.text! as CVarArg); post .appendFormat("logParams=%@", "1" as CVarArg); self.load(url: URL(string: url)!, params: post as String,name: fileName) GlobalData.sharedInstance.showLoader() |
Note:
self.load() -> is function which make request .
Here we are downloading .pdf file but you can download any file by adding the extension of file.
2: Now we have to make HTTP request to server and download to local directory.
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
func load(url: URL, params:String, name:String){ let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig) var request = try! URLRequest(url: url, method: .post) let postString = params; request.httpBody = postString.data(using: .utf8) let customerId = defaults.object(forKey:"customerId") as! String; request.addValue(customerId, forHTTPHeaderField: "customerId") 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)") GlobalData.sharedInstance.dismissLoader() } do{ let largeImageData = try Data(contentsOf: tempLocalUrl) let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let fileURL = documentsDirectoryURL.appendingPathComponent(name); if !FileManager.default.fileExists(atPath: fileURL.path) { do { try largeImageData.write(to: fileURL) let AC = UIAlertController(title:GlobalData.sharedInstance.language(key: "success"), message:GlobalData.sharedInstance.language(key: "filesavemessage"), preferredStyle: .alert) let okBtn = UIAlertAction(title: "ok", style: .default, handler: {(_ action: UIAlertAction) -> Void in self.documentPathUrl = fileURL as NSURL; self.performSegue(withIdentifier: "showFileData", sender: self) }) 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: { }) } catch { print(error) } } else { print("Image Not Added") } }catch{ print("error"); } do { } catch (let writeError) { } } else { GlobalData.sharedInstance.dismissLoader() print("Failure: %@", error?.localizedDescription); } } task.resume() } |
Note: tempUrl – is path of file directory where the actual data is there so we are fetching the data and write to file .
Now you can see the file also by fetching your file manager.