How do i exactly export a csv file from iOS written in swift? - ios

I am trying to export an cvs file.
With the following code i manage to get the file
let fileName = "sample.csv"//"sample.txt"
#IBAction func createFile(sender: AnyObject) {
let path = tmpDir.stringByAppendingPathComponent(fileName)
let contentsOfFile = "No,President Name,Wikipedia URL,Took office,Left office,Party,Home State\n1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,4/03/1797,Independent,Virginia\n2,John Adams,http://en.wikipedia.org/wiki/John_Adams,4/03/1797,4/03/1801,Federalist,Massachusetts\n3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,4/03/1801,4/03/1809,Democratic-Republican,Virginia\n4,James Madison,http://en.wikipedia.org/wiki/James_Madison,4/03/1809,4/03/1817,Democratic-Republican,Virginia\n5,James Monroe,http://en.wikipedia.org/wiki/James_Monroe,4/03/1817,4/03/1825,Democratic-Republican,Virginia\n6,John Quincy Adams,http://en.wikipedia.org/wiki/John_Quincy_Adams,4/03/1825,4/03/1829,Democratic-Republican/National Republican,Massachusetts"
//"Sample Text repacement for future cvs data"content to save
// Write File
do {
try contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
print("File sample.txt created at tmp directory")
} catch {
print("Failed to create file")
print("\(error)")
}
}
// Share button
#IBAction func shareDoc(sender: AnyObject) {
print("test share file")
docController.UTI = "public.comma-separated-values-text"
docController.delegate = self//delegate
docController.name = "Export Data"
docController.presentOptionsMenuFromBarButtonItem(sender as! UIBarButtonItem, animated: true)
//}
}
When i click the share file button in the simulator i see the following:
and with quick look it shows
So the next thing i did was testing with my iphone 5 and i tried to email sample.csv but i am only getting the message body and not the csv file???
how can i actually email the .csv file?
which export possibilities are there?

In order to email the .csv file, you can do the following:
Add this import to the top of the class. It allows you to use MFMailComposeViewController, which is a way to send emails.
import MessageUI
Generate your data, a sample I have done is:
// Creating a string.
var mailString = NSMutableString()
mailString.appendString("Column A, Column B\n")
mailString.appendString("Row 1 Column A, Row 1 Column B\n")
mailString.appendString("Row 2 Column A, Row 2 Column B\n")
// Converting it to NSData.
let data = mailString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
// Unwrapping the optional.
if let content = data {
print("NSData: \(content)")
}
Generate the MFMailComposeViewController
// Generating the email controller.
func configuredMailComposeViewController() -> MFMailComposeViewController {
let emailController = MFMailComposeViewController()
emailController.mailComposeDelegate = self
emailController.setSubject("CSV File")
emailController.setMessageBody("", isHTML: false)
// Attaching the .CSV file to the email.
emailController.addAttachmentData(data!, mimeType: "text/csv", fileName: "Sample.csv")
return emailController
}
// If the view controller can send the email.
// This will show an email-style popup that allows you to enter
// Who to send the email to, the subject, the cc's and the message.
// As the .CSV is already attached, you can simply add an email
// and press send.
let emailViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(emailViewController, animated: true, completion: nil)
}
In your case, as you have already created the file, you can simply attach that directly by changing the line where the CSV is attached to the mail for:
emailController.addAttachmentData(NSData(contentsOfFile: "YourFile")!, mimeType: "text/csv", fileName: "Sample.csv")
Answer based on: Attach csv to email xcode ,
Create CSV file in Swift and write to file

Creating CSV file in Swift
class ViewController: UIViewController {
var taskArr = [Task]()
var task: Task!
override func viewDidLoad() {
super.viewDidLoad()
task = Task()
for _ in 0..<5 {
task.name = "Raj"
task.date = "\(Date())"
task.startTime = "Start \(Date())"
task.endTime = "End \(Date())"
taskArr.append(task!)
}
creatCSV()
}
// MARK: CSV file creating
func creatCSV() -> Void {
let fileName = "Tasks.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Date,Task Name,Time Started,Time Ended\n"
for task in taskArr {
let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n"
csvText.append(newLine)
}
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
}
}
Task Model class
class Task: NSObject {
var date: String = ""
var name: String = ""
var startTime: String = ""
var endTime: String = ""
}
CSV output show as below format

SWIFT 5
func creatCSV() {
let fileName = "exportar_serv.csv"
/* CREAR UN ARCHIVO NUEVO EN EL DIRECTORIO PRINCIPAL */
guard let path = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName) as NSURL else {
return }
var csvText = "id,name,imageName\n"
for task in taskArr {
let x : Int64 = task.id!
let id2 = String(x)
let newLine = "\(id2),\(task.name),\(task.imageName)\n"
csvText.append(newLine)
} // for
do {
try csvText.write(to: path as URL, atomically: true, encoding: String.Encoding.utf8)
print("DATOS GUARDADOS")
} catch {
print("Failed to create file")
print("\(error)")
} // catch
} // CreateCSV

Swift 5.0.1, Xcode 10.2.1 version
private func injectExportButton() {
var csvIcon: UIImage
switch self.theme {
case .dark:
csvIcon = UIImage(named: "csv-export.dark", in: Bundle.framework)!
case .light:
csvIcon = UIImage(named: "csv-export.light", in: Bundle.framework)!
}
let imgWidth = csvIcon.size.width
let imgHeight = csvIcon.size.height
let button: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: imgWidth, height: imgHeight))
button.setBackgroundImage(csvIcon, for: UIControl.State())
button.alpha = 0
button.addTarget(self, action: #selector(csvExportButtonClicked), for: .touchUpInside)
UIView.animate(withDuration: 0.5) {
button.alpha = 1
}
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}
#objc private func csvExportButtonClicked() {
debugPrint("export clicked")
createCSV()
}
private func createCSV() -> Void {
let fileName = getDocumentsDirectory().appendingPathComponent("OutputD.csv")
var csvOutputText = "Result, Date, Name\n"
history.results.forEach { result in
let newLine = "\(String(describing: result.value)),\(String(describing: result.date)),\(String(describing: result.name))\n"
csvOutputText.append(newLine)
}
do {
try csvOutputText.write(to: fileName, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
let activity = UIActivityViewController(activityItems: ["your results", fileName], applicationActivities: nil)
present(activity, animated: true)
}
private func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}

Related

ErrorDomain Code=260 When attempting to read back a locally-stored image file

I'm making an application with one Core Data entity, Park, which is decoded from the data returned from an API request and stores the image url and local file/download location (if it has been downloaded) for each image as attributes. I created a computed property that returns a dictionary of ImageInfoObjects (which is a struct that basically just bundles the information together) based on the stored attributes. The first time I run the app, everything works fine but when I close the app and run it again it gives me the error "the file couldn't be opened because there is no such file". So I know there must be an issue with the way I'm storing the file paths in Core Data, or the way I'm reading them back to display the images. Any help would be appreciated. Code snippets below.
The method which catches the error:
func displayPhoto(_ object: ImageInfoObject, imageView: UIImageView) {
guard let location = object.downloadLocation else { return }
do {
let imageData = try Data(contentsOf: location)
let image = UIImage(data: imageData)
DispatchQueue.main.async {
imageView.image = image
}
} catch (let error) {
print(error)
}
}
The URLSessionDownloadDelegate method which is called once each image is finished downloading:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let fileManager = FileManager.default
guard let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first,
let sourceURL = downloadTask.originalRequest?.url,
let download = self.photoDownloads[sourceURL] else {
fatalError()
}
let lastPathComponent = sourceURL.lastPathComponent
let destinationURL = documentsPath.appendingPathComponent(lastPathComponent)
do {
if fileManager.fileExists(atPath: destinationURL.path) {
try fileManager.removeItem(at: destinationURL)
}
try fileManager.copyItem(at: location, to: destinationURL)
let index = download.imageInfoObject.index
let newImageInfoObject = ImageInfoObject(url: sourceURL, index: index, downloadLocation: destinationURL)
self.park?.photoInfoObjects[index] = newImageInfoObject
switch newImageInfoObject.index {
case 1:
displayPhoto(newImageInfoObject, imageView: self.photo1View)
case 2:
displayPhoto(newImageInfoObject, imageView: self.photo2View)
default:
break
}
try context?.save()
} catch {
print(error)
}
}
The computed property that stores and retrieves the paths from the CoreData entity. The NSManaged attributes are self.photo1_url, self.photo1_location, self.photo2_url, and self.photo2_location.
public var photoInfoObjects: Dictionary<Int, ImageInfoObject> {
get {
var dictionary: Dictionary<Int, ImageInfoObject> = [:]
var object: ImageInfoObject
if let photo1_url = self.photo1_url,
let url = URL(string: photo1_url) {
if let photo1_location = self.photo1_location {
let location = URL(fileURLWithPath: photo1_location)
object = ImageInfoObject(url: url, index: 1, downloadLocation: location)
object.isDownloaded = true
} else {
object = ImageInfoObject(url: url, index: 1)
}
dictionary[1] = object
}
var object2: ImageInfoObject
if let photo2_url = self.photo2_url,
let url = URL(string: photo2_url) {
if let photo2_location = self.photo2_location {
let location = URL(fileURLWithPath: photo2_location)
object2 = ImageInfoObject(url: url, index: 2, downloadLocation: location)
object2.isDownloaded = true
} else {
object2 = ImageInfoObject(url: url, index: 2)
}
dictionary[2] = object2
}
return dictionary
}
set {
self.photo1_url = newValue[1]?.url.absoluteString
self.photo1_location = newValue[1]?.downloadLocation?.path
self.photo2_url = newValue[2]?.url.absoluteString
self.photo2_location = newValue[2]?.downloadLocation?.path
}
}

GPUImage3 Unable to export video to Document Directory

I am using following source code to export filtered video to document directory but the exported file is corrupted/wrong.
Would you please go through following source and let me know where I am making mistake?
class ViewController: UIViewController {
#IBOutlet weak var renderView: RenderView!
var movie:MovieInput!
var writer:MovieOutput!
var filter:LookupFilter!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let bundleURL = Bundle.main.resourceURL!
let movieURL = URL(string:"sample_iPod.m4v", relativeTo:bundleURL)!
do {
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:true)
let fileURL = documentDirectory.appendingPathComponent("TestVideo.mov")
movie = try MovieInput(url:movieURL, playAtActualSpeed:true)
writer = try MovieOutput(URL: fileURL, size: Size(width: 100.0, height: 100.0))
filter = LookupFilter()
filter.lookupImage = PictureInput(image: UIImage(named: "Image")!)
movie --> filter --> renderView
movie.runBenchmark = true
movie.addTarget(writer)
movie.start()
writer.startRecording()
self.writer.finishRecording {
print("Written")
}
} catch {
print("Couldn't process movie with error: \(error)")
}
}
}
Simple answer: now you have 5 seconds .
self.movie.addTarget(writer)
self.movie.start()
self.filter --> self.writer
self.writer.startRecording()
let interval = 5 // now you have 5 seconds .
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + interval) {
self.writer.finishRecording {
print("Written")
}
}
To solve your problem forward,
You should extract out the record logic. put that in a filter button action.
like the following demo code .
#IBAction func capture(_ sender: AnyObject) {
if (!isRecording) {
do {
self.isRecording = true
let documentsDir = try FileManager.default.url(for:.documentDirectory, in:.userDomainMask, appropriateFor:nil, create:true)
let fileURL = URL(string:"test.mp4", relativeTo:documentsDir)!
do {
try FileManager.default.removeItem(at:fileURL)
} catch {
}
movieOutput = try MovieOutput(URL:fileURL, size:Size(width:480, height:640), liveVideo:true)
filter --> movieOutput!
movieOutput!.startRecording()
DispatchQueue.main.async {
// Label not updating on the main thread, for some reason, so dispatching slightly after this
(sender as! UIButton).titleLabel!.text = "Stop"
}
} catch {
fatalError("Couldn't initialize movie, error: \(error)")
}
} else {
movieOutput?.finishRecording{
self.isRecording = false
DispatchQueue.main.async {
(sender as! UIButton).titleLabel!.text = "Record"
}
self.movieOutput = nil
}
}
}
You miss one line code filter --> writer
movie.addTarget(writer)
movie.start()
filter --> writer
writer.startRecording()
self.writer.finishRecording {
print("Written")
}

Present preview of downloaded file directly in app

My application have file download option which downloads the file using alamofire download method. When the download completes i need to present the preview of the file without saving it to internal/cloud storage. How can i achieve this whatsapp like function that shows the preview after downloading the file.
func downloadFile(fileUrl: URL) {
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(fileUrl, to: destination)
.response(completionHandler: { (downloadResponse) in
self.dic.url = downloadResponse.destinationURL
self.dic.uti = downloadResponse.destinationURL!.uti
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
self.dic.presentOpenInMenu(from: rect, in: self.view, animated: true)
})
}
To present a preview of a file use Apple’s QuickLook framework that lets you embed previewing for a huge range of file types, including iWork documents, Microsoft Office documents, PDFs, images, and more, all without writing much code.
First, import the QuickLook framework, then make your view controller conform to the QLPreviewControllerDataSource protocol.
Reference:
https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller
https://github.com/gargsStack/QLPreviewDemo
https://www.appcoda.com/quick-look-framework/
Code:
class ViewController: UIViewController {
var previewItem = URL!
func downloadFile(fileUrl: URL) {
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(fileUrl, to: destination)
.response(completionHandler: { (downloadResponse) in
let previewController = QLPreviewController()
previewController.dataSource = self
self.previewItem = downloadResponse.destinationURL
self.present(previewController, animated: true, completion: nil)
})
}
}
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}
Here is one solution using Alamofire. Someone may help.
Steps:
Alamofire has excellent staff to direct download and also save/write
your file into disc.
Return a path where downloaded file saved.
Using UIDocumentInteractionController pass the file path
Then present this view
import Alamofire
extension UIViewController : UIDocumentInteractionControllerDelegate{
func downloadFileForPreview(fileName: String, fileExtension: String, filePath: String ) {
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileWithExtension = "file.\(fileExtension)"
let fileURL = documentsURL.appendingPathComponent(fileWithExtension)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
//UtilitySwift.showUniversalLoadingView(true)
Alamofire.download(filePath, to: destination).response { response in
debugPrint(response)
//UtilitySwift.showUniversalLoadingView(false)
if response.error == nil, let storeFilePath = response.destinationURL?.path {
//let image = UIImage(contentsOfFile: imagePath)
self.previewDocument(withFilePath: response.destinationURL)
print(storeFilePath)
}
else{
UtilitySwift.showErrorMessage(message: response.error?.localizedDescription ?? "Error occured when downloading" )
print(response.error?.localizedDescription ?? "")
}
}
}
// Converted to Swift 5.1 by Swiftify v5.1.29672 - https://objectivec2swift.com/
func previewDocument(withFilePath filePath: URL?) {
var documentInteractionController: UIDocumentInteractionController?
if filePath != nil {
// Initialize Document Interaction Controller
if let filePath = filePath {
documentInteractionController = UIDocumentInteractionController(url: filePath)
}
// Configure Document Interaction Controller
documentInteractionController?.delegate = self as UIDocumentInteractionControllerDelegate
//if not possible to open
if !documentInteractionController!.presentPreview(animated: true) {
documentInteractionController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true)
}
} else {
// error
print("file preview error")
}
}
//UIDocumentInteractionControllerDelegate
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
self
}
}
Call from any UIViewController
self.downloadFileForPreview(fileName: "file", fileExtension: fileExt ?? "", filePath: REPLACE_WITH_DOWNLOAD_URL)

How to access the .csv file directory through array

I have created save button which I guess going to create a .csv file to store x,y and name of the object on screen since I can't check it because I can't access the file its created
#IBAction func saveButton(_ sender: Any) {
let objectsName = stringObjectName.joined(separator: ",")
let coX = stringObjectX.joined(separator: ",")
let coY = stringObjectY.joined(separator: ",")
let fileName = getDocumentsDirectory().appendingPathComponent("output.csv")
CSVFilesName.append(fileName)
var csvText = "Name, Data X, Data Y\n"
let count = stringObjectName.count
if count > 0 {
for _ in 0..<(stringObjectName.count-1) {
let newLine = "\(objectsName),\(coX),\(coY)\n"
csvText.append(contentsOf: newLine)
}
}
do {
try csvText.write(to: fileName, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}
print(fileName)
}
after this I try to access the file call "output.csv" which it is suppose to store in document directory in another viewport. So, I created the method to pass the method from another view controller to current view controller by using and store CSVFile
var CSVFileName = [URL]()
func assignArray() {
let cameraVC = CameraViewController()
CSVFileName = cameraVC.CSVFilesName
print(CSVFileName)
}
and the problem start here since I have array which suppose to store file name in String
let fileNames = ["sth1.csv", "sth2.csv"]
but I can't find the convert CSVFileName from saving button to String, and replace "static array" into "dynamic array" and change the method below to get
URL from FileManager().default.url instead of fileURL to give TableViewController data to show and accessible
private func prepareFileURLS() {
for file in fileNames {
let fileParts = file.components(separatedBy: ".")
print(fileParts[0])
if let fileURL = Bundle.main.url(forResource: fileParts[0], withExtension: fileParts[1]) {
if FileManager.default.fileExists(atPath: fileURL.path) {
print(fileURL)
fileURLs.append(fileURL as NSURL)
}
}
}
print(fileURLs)
}
Here is the way you can read Your CSV file :
func filterMenuCsvData()
{
do {
// This solution assumes you've got the file in your bundle
if let path = Bundle.main.path(forResource: "products_category", ofType: "csv"){
// STORE CONTENT OF FILE IN VARIABLE
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
var rows : [String] = []
var readData = [String]()
rows = data.components(separatedBy: "\n")
for data in 0..<rows.count - 1{
if data == 0 || rows[data].contains(""){
continue
}
readData = rows[data].components(separatedBy: ",")
Category.append(readData[0])
if readData[2] != ""{
Occassions.append(readData[2])
}
selectedOccassionsRadioButtonIndex = Array(repeating: false, count: Occassions.count)
selectedCategoryRadioButtonIndex = Array(repeating: false, count: Category.count)
}
}
} catch let err as NSError {
// do something with Error}
print(err)
}
}

UIDocumentInteractionController not working

In my application I want to download various types of files and exports so that the user can open the file with the application that opens this type of file. I'm trying to use the UIDocumentInteractionController but after downloading save it to my device and trying to open it several problems happen. With .docx the application breaks and with other files it does not appear to encode the file. What can I be doing wrong?
When I try to share the file through the airdrop I get an error that says the file is invalid.
When I share with iBooks I get the message '' NSInternalInconsistencyException ', reason:' UIDocumentInteractionController has gone away prematurely! " And the app breaks
This is my code:
func loadArchiveAtIndex(sender: NSNotification){
let itemIndex = sender.userInfo!["index"] as! Int
let archiveKey = sender.userInfo!["downloadKey"] as! String
self.downloadingItens.append(itemIndex)
SQLiteDataController().getTokenSincronismo({
(Valido, Retorno, Token, Tipo) -> Void in
if Valido == true{
switch Retorno {
case 9: // Retorno Válido
let params = [
"tokenSincronizacao":"\(Token)",
"chaveProdutoBiblioteca":"\(archiveKey)"
]
Alamofire.request(.GET, "\(_URLPREFIX)/WSMhobErpServico/api/sincronizar/ProdutoBiblioteca/ObtemProdutoBiblioteca", parameters: params).responseJSON { (response) in
if response.result.isFailure {
print(response.result.error)
} else {
let result = response.result.value
if let archive = result?["ProdutoBiblioteca"] as? NSDictionary{
let bytes = archive.objectForKey("Arquivo") as! String
let name = archive.objectForKey("NomeArquivo") as! String
let data = NSData.init(base64EncodedString: bytes, options: .IgnoreUnknownCharacters)
let url = NSURL.init(string: name.lowercaseString)
data?.writeToURL(url!, atomically: true)
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent((name.lowercaseString))
let dic = UIDocumentInteractionController.init(URL: fileURL!)
dic.delegate = self
dic.presentOpenInMenuFromRect(CGRect.init(x: 0, y: 0, width: 200, height: 200), inView: self.view, animated: true)
var arrayIndex = 0
for item in self.downloadingItens {
let i = item
if i == itemIndex {
self.downloadingItens.removeAtIndex(arrayIndex)
NSNotificationCenter.defaultCenter().postNotificationName("reloadTable", object: nil, userInfo: ["itens":self.downloadingItens])
break
}
arrayIndex = arrayIndex + 1
}
} else {
print("erro")
}
}
}
break
default:
self.showError("Atenção", message: "Não foi Possivel Processar a sua Solicitação")
break
}
}else{
self.showError("Atenção", message: "Não foi Possivel Processar a sua Solicitação")
}
}, sincFull:true)
}
func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController) -> UIView? {
return self.view
}
func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController) -> CGRect {
return self.view.frame
}
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
Okay I got your point.
I have reviewed your code and I think the problem is in below line
let dic = UIDocumentInteractionController.init(URL: fileURL!)
dic.delegate = self
You are creating object of UIDocumentInteractionController inside block so when block will be out of memory or deallocated your UIDocumentInteractionController object will also be released.
So make UIDocumentInteractionController object global. Declare object globally for that class and then assign value inside the block.
let name = archive.objectForKey("NomeArquivo") as! String
let data = NSData.init(base64EncodedString: bytes, options: .IgnoreUnknownCharacters)
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent((name.lowercaseString))
data?.writeToURL(fileURL!, atomically: true)

Resources