how to send files with url in device in swift 3? - ios

I have a mini file manager in my app that user can copy files with iTunes - FileSharing into the app and then upload them to the server
I used post Method But Didn't worked for me! I got the files url in the device But I don't know this way that I choose is right or not
here is the file detection codes
// Get the document directory url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)
// if you want to filter the directory contents you can do like this:
let pdfFiles = directoryContents.filter{ $0.pathExtension == "pdf" }
print("pdf urls:",pdfFiles)
filesurl = pdfFiles
print(pdfFiles.count)
filesCount = pdfFiles.count
let pdfFileNames = pdfFiles.map{ $0.deletingPathExtension().lastPathComponent }
print("pdf list:", pdfFileNames)
filestext = pdfFileNames
} catch let error as NSError {
print(error.localizedDescription)
}
and here is the Url of files in the device
var names = String()
let rows = fileTableView.indexPathsForSelectedRows.map{$0.map{$0.row}}
print(rows!)
for i in rows! {
print(filesurl[i])
print(filestext[i])
names.append("\(filestext[i])")
fileManagerViewController.filesForUpload.append(filesurl[i])
}
and here is the post method that I used
let parameters = ["myfile" : "\(fileManagerViewController.filesForUpload)"]
print(parameters)
guard let url = URL(string: "http://example.com/api/file?api_token=\(EmailSignInViewController.api_token)") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data , response , error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()

Related

Why not getting response from one URL?

I am using URLSession. I am not receiving any error or response.
It works with one url. However it does not work with one another.
I have also tried percentencoding. But it doesn't work too.
The code is below
let urlString = "https://stark-spire-93433.herokuapp.com/json"//This is not working
//let urlString = "https://jsonplaceholder.typicode.com/todos"//This is working
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)//URLSession.shared
var request = URLRequest(url: URL(string:urlString)!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: [], options: [])
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print("response---",response)
print("error--",error)
if data != nil {
let json = try? JSONSerialization.jsonObject(with: data!)
print("JSOn",json)
} else {
print("error data is nil")
}
})
task.resume()
Too cumbersome code.
This is sufficient
let url = URL(string:"https://stark-spire-93433.herokuapp.com/json")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { print(error!); return }
do {
let json = try JSONSerialization.jsonObject(with: data)
print("JSOn",json)
} catch {
print(error)
}
}
task.resume()

Download PDF and save to the "Files" in iPhone, not to the app data, Swift [duplicate]

This question already has answers here:
How to write a file to a folder located at Apple's Files App in Swift
(2 answers)
Closed 3 years ago.
I tried downloading pdf files with the below code. Here it's storing in the app data. But I need to show the downloaded pdf in "Files" folder in iPhone.
// 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: "http://swift-lang.org/guides/tutorial.pdf")
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()
Is it possible??
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()

URLSession datatask accessing older version of website?

I am using URLSession to scrape JSON data from my website. My code was throwing various errors relating to casting types, so I added some print statements to my code and found that this function is for some reason accessing an older version of my site. I have since updated the website's data, and verified that the new data is displaying properly both through visiting the website myself and using Rested. However, the print statements in the code below yield old data. The code does not read data from the disk so I am not sure why this is happening.
I have removed the website's link from my code for privacy purposes, but otherwise the function can be found below.
func websiteToDisk() {
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
let defaultSession = URLSession(configuration: config)
let url = URL(string: someURL)
let task = defaultSession.dataTask(with: url!) { data, response, error in
do {
print("Getting information from website")
if let error = error {
print(error.localizedDescription)
} else if let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
//do {
let jsonDecoder = JSONDecoder()
print("about to dcode")
let decodedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]//try jsonDecoder.decode([String: [String]].self, from: data)
print(decodedData)
print("accessing dictionary")
print(decodedData!["busLoops"])
let toWrite = decodedData!["busLoops"] as! [String]
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let busLoopsURL = documentDirectoryURL.appendingPathComponent("busLoops").appendingPathExtension("json")
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(toWrite)
try jsonData.write(to: busLoopsURL)
//} catch { print(error)}
}
}
catch { print(error)}
}
task.resume()
}
Try ignore local cache data
guard let url = URL(string: "http://....") else{
return
}
let request = NSMutableURLRequest(url: url)
request.cachePolicy = .reloadIgnoringCacheData
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, resp, error) in
}
task.resume()

How to read data from file placed in server through url link in ios swift (4)?

I have written code for retrieving data from file or download that file and show in your phone. But I don't understand why it is not displaying data. When I opened that file it shows blank and but it is printing some hexadecimal code in a console.
I am very new to this IOS development, kindly please help me this. I want to retrieve data from the server through a link, and display it on the mobile.
Thanks in advance you can help with some alternate way.
Below is my code
let username = "xxxx"
let password = "xyz"
let loginData = String(format: "%#:%#", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://demo.xyz.com/dctm-rest/repositories/iol_ref2/objects/0900a1848039590d/content-media?format=crtext&modifier=&page=0")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
let taskk = 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 {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if paths.count > 0
{
documentsDirectory = paths.first!
}
var fileURL : URL = URL(fileURLWithPath: documentsUrl!.absoluteString+filename)
if(mimetype == "text/plain"){
fileURL = URL(fileURLWithPath: documentsUrl!.absoluteString+filename+".txt")
}else if(mimetype == "application/pdf"){
fileURL = URL(fileURLWithPath: documentsUrl!.absoluteString+filename+".pdf")
}
print(fileURL)
let dataFromURL = NSData(contentsOf: tempLocalUrl)
dataFromURL?.write(to: fileURL, atomically: true)
print(dataFromURL)
try FileManager.default.copyItem(at: tempLocalUrl, to: fileURL)
OperationQueue.main.addOperation {
self.activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
let documentController = UIDocumentInteractionController.init(url: fileURL)
documentController.delegate = self as? UIDocumentInteractionControllerDelegate
documentController.presentPreview(animated: true)
}
} catch (let writeError) {
print("error writing file : \(writeError)")
}
} else {
print("Failure: %#", error?.localizedDescription);
}
}
taskk.resume()

Swift - Downloaded zip file creating .cpgz file after extract.

Downloading a zip file from Dropbox or Google drive URL results in a zip file that is extracted to cpgz file. Using below code to accomplish download of zip file. I want to know is there any specific way to download any zip file so that it does not result in cpgz cycle.
if let zipUrl = URL(string: "https://www.dropbox.com/s/n785nwy2tbaxgz8/app_dfu_package_1.zip?dl=0") {
// 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(zipUrl.lastPathComponent)
//print(destination)
var urlRequest = URLRequest.init(url: zipUrl)
urlRequest.httpMethod = "get"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-Type")
// check if it exists before downloading it
if FileManager().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: urlRequest, 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 location = location, error == nil
else { return }
do {
try FileManager.default.moveItem(at: location, to: destination)
print("file saved")
} catch {
print(error)
}
}).resume()
}
}
How we can fix it in Swift code
Sharing the link that solved my issue. I was also getting zip file's mime type text/html. Changing the dropbox url solved my query.
How to download a Dropbox share linkage (aimed at a zip file) to local
if let zipUrl = URL(string: "https://www.dropbox.com/s/n785nwy2tbaxgz8/app_dfu_package_1.zip?dl=1") {
// 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(zipUrl.lastPathComponent)
//print(destination)
var urlRequest = URLRequest.init(url: zipUrl)
urlRequest.httpMethod = "get"
urlRequest.setValue("application/json", forHTTPHeaderField: "content-Type")
// check if it exists before downloading it
if FileManager().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: urlRequest, 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,
let location = location, error == nil
else { return }
do {
try FileManager.default.moveItem(at: location, to: destination)
print("file saved")
print("Mime Type:- \(mimeType)")
} catch {
print(error.localizedDescription)
}
}).resume()
}
}
After making URL change(dl=0 to dl=1), the mime type I get is application/binary. It solved .zip to .cpgz cycles on the extraction of the zip file.
First make sure that your server is returning a zip file itself or not by adding following code :
let response = response as! HTTPURLResponse
guard (200...299).contains(response.statusCode) else {
… deal with the server-side error …
}
guard response.mimeType == "application/zip" else {
… deal with the bogus `Content-Type` …
}
If its a zip file then it will execute forward and you have to do like follows to save that file in disk:
let destinationDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let destination = destinationDir.appendingPathComponent("SomeFileName.zip")
try data!.write(to: destination)

Resources