How to upload CSV file in google drive in swift 3 - ios

I am using google drive SDK for uploading CSV file. I used code given in google but error is coming
func create(){
let fileData = FileManager.default.contents(atPath: "FL_insurance_sample.csv")
let folderId: String = self.fileId!
let metadata = GTLRDrive_File.init()
metadata.name = "FL_insurance_sample"
metadata.mimeType = "application/vnd.google-apps.spreadsheet"
metadata.parents = [folderId]
let uploadParameters = GTLRUploadParameters(data: fileData! , mimeType: "text/csv")
uploadParameters.shouldUploadWithSingleRequest = true
let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
query.fields = "id"
self.service.executeQuery(query, completionHandler: {(ticket:GTLRServiceTicket, object:Any?, error:Error?) in
if error == nil {
// print("File ID \(files.identifier)")
}
else {
print("An error occurred: \(error)")
}
})
}
It showing nil error on uploadParameters at fileData. Can anyone help me out.

Variable fileData is nil because you've passed the wrong file path. To get correct file path use:
guard let filePath = Bundle.main.path(forResource: "FL_insurance_sample", ofType: "csv") else {
print("No such file in bundle")
// handle situation
return
}
guard let fileData = FileManager.default.contents(atPath: filePath) else {
print("Can't read file")
// handle situation
return
}
// upload fileData

Related

Rename the download pdf file using swift iOS

I am successfully downloading a PDF from api end point. Once pdf is downloaded, the title of pdf is : PDF document.pdf .
How to change the title of PDF?
I tried to update metadata of PDF using PDFDocumentAttribute (see below), but it is not working.
var metadata = pdfDocument.documentAttributes!
metadata[PDFDocumentAttribute.subjectAttribute] = "subject attribute"
metadata[PDFDocumentAttribute. titleAttribute] = "title attribute"
pdfDocument.documentAttributes = metadata
Note: I am not using FileManager
How I am fetching PDF:-
let task = session.dataTask(with: urlRequest) { (data, _, error) in
DispatchQueue.main.async {
guard let unwrappedData = data, error == nil else {
completion(.failure(error ?? Constants.dummyError))
return
}
guard let pdfDocument = PDFDocument(data: unwrappedData) else {
completion(.failure(error ?? Constants.dummyError))
return
}
completion(.success(pdfDocument))
}
}
try this:
pdfDocument.documentAttributes?["Title"] = "my title attribute"
or
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
Similarly for PDFDocumentAttribute.subjectAttribute.
The above will set the Title of your document, and when you save it, the file name will be whatever file name you give it.
EDIT-1: saving the pdfDocument to a file with a chosen file name.
DispatchQueue.main.async {
guard let unwrappedData = data, error == nil else {
completion(.failure(error ?? Constants.dummyError))
return
}
guard let pdfDocument = PDFDocument(data: unwrappedData) else {
completion(.failure(error ?? Constants.dummyError))
return
}
// set the Title
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
do {
// save the document to the given file name ("mydoc.pdf")
let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydoc.pdf") // <-- here file name
pdfDocument.write(to: docURL)
print("\n docUrl: \(docURL.absoluteString)\n")
}
catch {
print("Error \(error)")
}
completion(.success(pdfDocument))
}

How to upload pdf file into firebase by using iOS

Can I upload pdf files into firebase using Swift?.
If it is possible please share me the code.
I'm using the below code
let proofRef = filesstorgRef.child(timestamp)
let uploadTask = proofRef.putData(data, metadata: nil, completion: { (metadata, error) in
if error != nil {
//print("Failed to upload image:", error)
return
}
if let fileUrl = metadata?.downloadURL()?.absoluteString {
completion(fileUrl)
}
})
uploadTask.observe(.progress) { (snapshot) in
if (snapshot.progress?.completedUnitCount) != nil {
print("ImageUploadingPerCent=== \(String(describing: snapshot.progress?.completedUnitCount))")
}
}
uploadTask.observe(.success) { (snapshot) in
print("ImageUploading Success")
}
uploadTask.observe(.failure) { (snapshot) in
LoadingView.sharedInstance.visible(visible: false)
print("ImageUploading failure")
}
thanks in advance
// Get the default app firebse storage reference
let FIRStorage = Storage.storage()
// reference of the storage
let storageRef = FIRStorage.reference()
// You have to get the file URL from disk or anywhere
let filePath = Bundle.main.path(forResource: "mypdf", ofType: "pdf")
let filePathURL = URL(fileURLWithPath: filePath!)
// Create a reference/Path on firebase database, where you want to upload your file
let fileRef = storageRef.child("firebase path with filename")
// from this you cant upload the file on fileRef path
let uploadTask = fileRef.putFile(from: filePathURL, metadata: nil) { metadata, error in
guard let metadata = metadata else {
// error!
return
}
let metadataSize = metadata.size
// get the download url of this file
fileRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// error!
return
}
}
}
Try this code.

How to get rid of the word optional before a url saved in firebase?

Currently I am saving the url of images stored in the firebase database. However I am getting the word optional before the url. As seen bellow.
"Optional(https:URL.HERE)"
The following is the code block where the saving happens:
if let imageData = UIImageJPEGRepresentation(image, 0.8) {
let metadata = storageRef //.child("poop/")
let uploadTask = metadata.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// You can also access to download URL after upload.
storageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
return
}
let imgURL = url
//database integration
let ref = Database.database().reference()
let usersRef = ref.child("usersPosts")
let uid = Auth.auth().currentUser?.uid
let newUserRef = usersRef.child(uid!)
//creates a child for email and password (i think we shud store password so we can tell sumone what it is inmediatly, maybe)
newUserRef.setValue(["Image": "\(imgURL)"])
}
}
// For progress
uploadTask.observe(.progress, handler: { (snapshot) in
guard let progress = snapshot.progress else {
return
}
let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
progressBlock(Double(percentage))
})
} else {
completionBlock(nil, "Image could not be converted to Data.")
}
You are getting Optional... because imgURL is optional. And imgURL is optional because you assigned it from url which is optional.
Since you already unwrapped url in the guard statement, just use downloadURL instead of creating imgURL.
Remove:
let imgURL = url
And replace the use of imgURL with downloadURL which is the properly unwrapped version of url from the guard.
newUserRef.setValue(["Image": "\(downloadURL)"])

Error uploading file to Amazon S3

I want t upload a csv file from my iOS App (written in Swift) to my amazon S3 bucket. To do this I'm using following code:
//Create
let fileName = "Export.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
csvText = CreateCSVAccount()
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf32BigEndian)
//Prepare Upload
let uploadingFileURL = path
let uploadRequest = AWSS3TransferManagerUploadRequest()
let Bucketname = "mybucket/CSV"
uploadRequest?.bucket = Bucketname
uploadRequest?.key = "mycsvfile.csv"
uploadRequest?.body = uploadingFileURL!
//Upload File
transferManager.upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
if let error = task.error as NSError? {
if error.domain == AWSS3TransferManagerErrorDomain, let code = AWSS3TransferManagerErrorType(rawValue: error.code) {
switch code {
case .cancelled, .paused:
break
default:
print("Error Contact uploading: \(String(describing: uploadRequest?.key)) Error: \(error)")
}
} else {
print("Error Contact uploading: \(String(describing: uploadRequest?.key)) Error: \(error)")
}
return nil
}
let uploadOutput = task.result
print("Upload complete for: \(String(describing: uploadRequest?.key))")
print("uploadOutput: \(String(describing: uploadOutput))")
return nil
})
} catch {
print("Failed to create file")
print("\(error)")
}
The problem is sometimes it works and sometimes I'm receiving the following error:
Message=You did not provide the number of bytes specified by the Content-Length HTTP header, NumberBytesExpected=412, Code=IncompleteBody, RequestId=075D1F5B0A377E89
Can somebody please help me?
Thank you very much in advance!
Add the contentLength header to your request.
That is:
uploadRequest?.contentLength = 1234
where 1234 is an NSNumber representing the number of bytes in body

unable to overwrite the text file

I'm trying to overwrite the existing file everytime the application is started. I have tried two things both are not working.
1) I'm trying to create the file getting downloaded from online server with the same name but the data in the file is not getting updated, my code is..
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("Splash.text")
let fileURL = URL(string:(defaults.object(forKey: "MainAddress") as! String).appending(filedownloadLink)
print("proper url = \(String(describing: fileURL))")
let sessionConfig = URLSessionConfiguration.default
let session1 = URLSession(configuration: sessionConfig)
print("splash file url \(destinationFileUrl)")
let request = URLRequest(url:fileURL!)
let task1 = session1.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)
let fileManager = FileManager.default
// Check if file exists
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task1.resume()
2) then i tried checking for the file before creating it, and if it exists then i'm deleting it. but once the file is deleted it is not getting opened with an error saying file "splash.text" doesnot exist. below is the code
do{
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("Splash.text").path
let fileManager1 = FileManager.default
if fileManager1.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
try fileManager1.removeItem(atPath: filePath)
} else {
print("FILE NOT AVAILABLE")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
and after this code I'm calling the code of method 1. I'm not sure why it is not getting created again for 2nd method, or why it is not overwritting it in 1st.

Resources