Download and view document in ios from firebase storage - ios

I have a firebase storage link of a document which I want to download in my ios device's Document directory and then view it from there using QuickLook Module.
I am able to download document in iOS device but it is not saving with the name i am providing.
I want to create following directory structure and then need to save document in "doc" folder.
Documents/chat/doc
following code is to create "/chat/doc" inside Iphone's Document directory. Where folderName will contain "/chat/doc".
func createDocument(folderName: String ,completion: #escaping(Bool,String)->()){
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
if let documentsDirectory = path{
//
let docDirectoryPath = documentsDirectory.appending(folderName)
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: docDirectoryPath) {
do {
try fileManager.createDirectory(atPath: docDirectoryPath,
withIntermediateDirectories: true,
attributes: nil)
//return path on success
completion(true,docDirectoryPath)
return
} catch {
print("Error creating folder in documents dir: \(error.localizedDescription)")
completion(false,error.localizedDescription)
return
}
}
completion(true,docDirectoryPath)
}
}
after creating folder i want to download document and need to store in newly created folder in Document Directory.
Following code will download document.
func downloadDocument(){
createDocument(folderName: "/chat/doc") { (status, path) in
if let docURL = self.documentURL{
if status{
//folder is created now download document
let docDownloadRef = Storage.storage().reference(forURL: docURL)
//get documents metadata from firebase to get document name
docDownloadRef.getMetadata { metadata, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
//get document name from metadata
if let fileName = metadata?.name{
//create file system url to store document
let docsurl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("chat/\(fileName)")
_ = docDownloadRef.write(toFile: myurl) { url, error in
if let error = error {
print(error.localizedDescription)
} else {
// Local file URL for document is returned
print("doc url \(url?.absoluteString)")
}
}
}
}
}
}else{
//folder is not created show document using online location
}
}
}
}
Ultimate goal is to achieve something like this "Documents/chat/doc/abc.doc"
but my code is not storing document using file name it stores like this "Documents/chat/doc" where doc is considered as a document not a folder.
Please help to let me know what I am doing wrong.
Thank you.

When you are creating url at below line, here you are missing the path for doc folder.
let myurl = docsurl.appendingPathComponent("chat/\(fileName)")
This will save to chat folder. You need to pass the same folder while creating i.e folderName: "/chat/doc" so it should be
let myurl = docsurl.appendingPathComponent("chat/doc/\(fileName)")

Related

SwiftUI | File found on simulator but not on iOS device

I'm trying to create a connection between my program and a database located in /Documents of the app. When the code is built using on the simulator, it successfully opens the database; however, when I run the code on an iOS device, it can't find the file.
This is the code that I use:
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
let db = try! Connection("\(path)/Database.db")
These are the contents of the variable path when I run the code on the simulator:
/Users/xxxx/Library/Developer/CoreSimulator/Devices/EFD14A1B-7207-4840-9ACE-8E44A269CC70/data/Containers/Data/Application/58D150B9-E242-4857-B06C-DA28C88A26D0/Documents
And these are the contents of the variable path when I run the code on an iOS device:
/var/mobile/Containers/Data/Application/4EC93D76-4E99-4552-855A-48C1D9346449/Documents
Xcode version: 12.0
iOS device: iPhone X
iOS version: 14.1
Edit
I tried to use this code to copy the database from the app bundle to the document directory, but it gives the error Unable to copy file:
copyFileToDocumentsFolder(nameForFile: "Database", extForFile: "db")
func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destURL = documentsURL.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
else {
print("Source File not found.")
return
}
let fileManager = FileManager.default
do {
try fileManager.copyItem(at: sourceURL, to: destURL)
} catch {
print("Unable to copy file")
}
}
You can use url or path: with this codes you get the address of your data base, but you have to have your database file already there when your app use this address to find your databace! if you use this address, without having real file there, your app will crash. So if you have problem about copying your databace file let me know!
Version: 1.0.0
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let databaseURL = appBaseURL.appendingPathComponent("Database").appendingPathExtension("db").standardizedFileURL
let databasePath = databaseURL.path
Update Version: 2.0.0
This codes down are the most simplest and cleanest code about copy and paste on planet Earth for Swift and SwiftUI! You can not find better than this:
// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 -add this one ("Supports opening documents in place" -> Yes) from (info.plist)
let fileName = "omid"
let fileExtension = "jpeg"
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
if FileManager.default.fileExists(atPath: appBaseURL.path)
{
print("appBaseFolder already exists!")
}
else
{
do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
catch{ print("Error in creating appBaseFolder!") }
}
if FileManager.default.fileExists(atPath: pasteFileURL.path)
{
print("The selected file already exists!")
}
else
{
do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
catch { print("Error with copying selected file!") }
}
Version: 3.0.0 (The GM Version)
//▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 - add this one ("Supports opening documents in place" -> Yes) from (info.plist)
//...........................................................
let fileName = "omid"
let fileExtension = "jpeg"
//...........................................................
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
//▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//...........................................................
if FileManager.default.fileExists(atPath: appBaseURL.path)
{
print("appBaseFolder already exists!")
}
else
{
do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
catch{ print("Error in creating appBaseFolder!") }
}
//...........................................................
//...........................................................
if FileManager.default.fileExists(atPath: copyFileURL.path)
{
//...........................................................
if FileManager.default.fileExists(atPath: pasteFileURL.path)
{
print("The selected file already exists!")
}
else
{
do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
catch { print("Error with copying selected file!") }
}
//...........................................................
}
else
{
print("The selected file not exists for copy Action!")
}
//...........................................................
As I already mentioned in your last question the Bundle is read-only. you need to move/copy your database to another directory that you can read/write to it. If you don't want the user to have access to the file you should copy it to that application support directory:
extension URL {
static let database: URL = {
let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let bundleID = Bundle.main.bundleIdentifier ?? "company name"
let subDirectory = applicationSupport.appendingPathComponent(bundleID, isDirectory: true)
let destination = subDirectory.appendingPathComponent("Database.db")
if !FileManager.default.fileExists(atPath: destination.path) {
let source = Bundle.main.url(forResource: "Database", withExtension: "db")!
do {
try FileManager.default.createDirectory(at: subDirectory, withIntermediateDirectories: true, attributes: nil)
print("directory created")
try FileManager.default.copyItem(at: source, to: destination)
print("file copied successfully")
} catch {
print("Unable to copy file. return the bundle read-only version")
return source
}
}
print("database found return app suport database read-write url")
return destination
}()
}
let dbURL = URL.database
The Mac (and by extension the Simulator) has a case-insensitive file system. iOS has a case-sensitive file system. If it's working on the simulator, but not the device, I expect the capitalization of your database filename is incorrect. The most likely mistake would be that it's database.db rather than Database.db.

iOS file path is changing at every launch/rerun the application

I have an issues in changing the file path at every launch of the app.
I have a file("AppConstant.json") in application bundle, and this file I need to copy into application document directory. I am successfully saving "AppConstant.json" file inside the created user folder "MyFolder" on Document directory.
But the problem is when I relaunch the application second time, it's not showing the same path. Also I am using relativepath, but still it not getting.
here is the code
// calling the directory
let stringAppConstant = copyFileFromBundleToDocumentDirectory(resourceFile: "AppConstant", resourceExtension: "json")
// saving or get exit file path
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) -> String
{
var stringURLPath = "Error_URLPath"
let fileManager = FileManager.default
let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
if !fileManager.fileExists(atPath: newDestPath.path) {
do {
try fileManager.createDirectory(atPath: newDestPath.path,withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", newDestPath.path)
} catch {
print("Error in creating folder :::",error.localizedDescription);
}
}
else {
print("Folder is already exist!")
}
if fileManager.fileExists(atPath: fullDestPath.path) {
print("File is exist in ::: \(fullDestPath.path)")
stringURLPath = fullDestPath.path
}
else {
do {
try fileManager.copyItem(atPath: sourcePath, toPath: fullDestPath.path)
print("Saved file successfully in :::", fullDestPath.path)
stringURLPath = fullDestPath.path
} catch {
print("Error in creating file ::: \(error.localizedDescription)")
}
}
return stringURLPath
}
Please help me, where I need to save the path in Sandbox. Is this right way what I implemented.
I am running in device and simulator, both path are different while relaunch
this is the path for first time launch:
/var/mobile/Containers/Data/Application/81B568A7-0932-4C3E-91EB-9DD62416DFE8/Documents/MyFolder/AppConstant.json
relaunch the application I am getting new path:
/var/mobile/Containers/Data/Application/3DAABAC3-0DF5-415B-82A5-72B204311904/Documents/MyFolder/AppConstant.json
NOTE: I create a sample project and I use this same code and it's working. But in existing project it's not working. I am using the same bundle id and profile only for both sample and project. Checked the file added reference, settings, version all are same.
Any idea?
The behavior that the container path changes periodically is normal.
These lines
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
contain a lot of mistakes
URL(string is the wrong API for file paths, it's URL(fileURLWithPath).
The second parameter of path(forResource:ofType:) must not have a leading dot.
The API absoluteString is wrong as parameter of URL(fileURLWithPath
Not a real mistake but don't use NSURL in Swift.
It's highly recommended to use always the URL related API to concatenate paths and get the documents folder from FileManager. Further it's good practice to make the method throw the real error rather than returning a meaningless literal string. And NSSearchPathForDirectoriesInDomains is outdated and should not be used in Swift.
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) throws -> URL
{
let sourceURL = Bundle.main.url(forResource: resourceFile, withExtension: resourceExtension)!
let fileManager = FileManager.default
let destFolderURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("MyFolder")
let fullDestURL = destFolderURL.appendingPathComponent(resourceFile).appendingPathExtension(resourceExtension)
if !fileManager.fileExists(atPath: destFolderURL.path) {
try fileManager.createDirectory(at: destFolderURL, withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", destFolderURL.path)
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
} else {
print("Folder already exists!")
if fileManager.fileExists(atPath: fullDestURL.path) {
print("File exists in ::: \(fullDestURL.path)")
} else {
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
}
}
return fullDestURL
}
Edit 1:
Hi I created the new project and use the same code I posted in main, and it's working. But in the real project it not working.
Not sure what exactly going on in your project, try to debug it. It's part of development as well. :)
If you are in hurry to fix this issue in this weekend try to use the following code snippet.
// collect data from bundle
let constFileURL = Bundle.main.url(forResource: "AppConst", withExtension: "json")!
let data = try! Data(contentsOf: constFileURL)
// try to write data in document directory
do {
let constFileURL = try saveFileInDocumentDirectory(filePath: "MyFolder/AppConst.json", data: data)
// use your `constFileURL`
} catch (let error as FileOperationError) {
switch error {
case .fileAlreadyExists(let url):
let data = try! Data(contentsOf: url)
print(String(data: data, encoding: .utf8))
case .IOError(let error):
print("IO Error \(error)")
}
} catch {
print("Unknown Error \(error)")
}
// Helpers
enum FileOperationError: Error {
case fileAlreadyExists(url: URL)
case IOError(Error)
}
func saveFileInDocumentDirectory(filePath: String, data: Data) throws -> URL {
// final destination path
let destURLPath = fullURLPathOf(filePath, relativeTo: .documentDirectory)
// check for file's existance and throw error if found
guard FileManager.default.fileExists(atPath: destURLPath.path) == false else {
throw FileOperationError.fileAlreadyExists(url: destURLPath)
}
// Create Intermidiate Folders
let intermidiateDicPath = destURLPath.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: intermidiateDicPath.path) == false {
do {
try FileManager.default.createDirectory(at: intermidiateDicPath, withIntermediateDirectories: true, attributes: nil)
} catch {
throw FileOperationError.IOError(error)
}
}
// File Writing
do {
try data.write(to: destURLPath, options: .atomic)
} catch {
throw FileOperationError.IOError(error)
}
return destURLPath
}
func fullURLPathOf(_ relativePath: String, relativeTo dic:FileManager.SearchPathDirectory ) -> URL {
return FileManager.default.urls(for: dic, in: .userDomainMask).first!.appendingPathComponent(relativePath)
}
Original Answer
Why don't you just return "MyFolder/\(fileName)" on successful file operation? If you need to access the path later you can always do that using FileManager APIs.
let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let constFilePath = docDir.appendingPathComponent("MyFolder/\(fileName)")
// Access const file data
do {
let fileData = try Data(contentsOf: constFilePath)
// Use you data for any further checking
} catch {
// Error in reading file data
print("Error in file data access : \(error)")
}

Save and get image from folder inside Documents folder on iOS wrong path

On application launch I'm creating a folder inside the Documents directory, if there is none there already. This works great!
I'm downloading some images and would like to save them to use them later.
My problem is that my code seems to store the files in a documents directory that is not the same that would be on the next app launch.
I know that since iOS8 the documents directory can change from launch to launch. So I'm always retrieving a path to the Documents folder. Could someone answer me why this code can't get the path to the image correctly?
func requestImage(let url: String,let isbn: String, numberInRow: Int){
var documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
documentsPath.appendContentsOf("/bookImages")
print("Image folder path is: \(documentsPath)")
///var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages
let pathComponent = isbn.stringByAppendingString(".jpg")
print("Suggested filename: \(pathComponent)") //1234567891234.jpg
let imagePath = documentsPath.stringByAppendingString("/\(pathComponent)")
print("Image to be saved at: \(imagePath)")
// /var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages/9788202350420.jpg
if (data != nil){
NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["YES" : "NSURLIsExcludedFromBackupKey"])
self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
}
}
When I would like to display these images I have this in the view controller
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let imageFolderPath = documentsPath.stringByAppendingString("/bookImages")
if let image = bookData.valueForKey("imageurl") as? String
{
print("Imagepath: \(self.imageFolderPath)/\(image)")
// /var/mobile/Containers/Data/Application/DB1F6FE9-1071-41A6-9E87-2A3D32ECD2B9/Documents/bookImages/9788202350420.jpg
let imagePath = self.imagePath.stringByAppendingString("/\(image)")
reuseableCell.bookCover.image = UIImage(contentsOfFile: imagePath)
}
I removed a lot of code that was not relevant. Why can't the image be displayed be found?
If anyone understand the error code, it is here:
BOMStream BOMStreamWithFileAndSys(int, off_t, size_t, int, char *, BomSys *): read: No such file or directory
Edit:
On application launch I'm searching for files in the Documents/bookImages and the files are there.
let paths: NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
if let documentDirectory = paths.firstObject{
do{
var path = documentDirectory as! String
path.appendContentsOf("/bookImages")
let documents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
for files in documents {
let urlForm = NSURL.fileURLWithPath((path) + "/" + files)
do{
try print("\(files): \(urlForm.resourceValuesForKeys([NSURLIsExcludedFromBackupKey])), with filepath: \(urlForm)")
//Prints out folder and files in the desired location
} catch let error as NSError{
print("Can't find key: \(error)")
}
}
}catch let error as NSError{
print("Can't retrieve contents: \(error)")
}
}
9788202350420.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6- ED2AF171D1AA/Documents/bookImages/9788202350420.jpg
9788203193538.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203193538.jpg
9788203254703.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203254703.jpg
I suspect the issue is happening because you didn't created the bookImages folder in the document directory. NSFileManager won't create the directories or sub-directories automatically.
// Creating directory
do
{
try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
NSLog("\(error.localizedDescription)")
}
// Saving image
if (data != nil)
{
// Also it would be better to check the file creation status
let status = NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["NSURLIsExcludedFromBackupKey" : "YES"])
if status
{
// File created
self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
}
else
{
// File creation failed, update your question on stack overflow, someone will surely help you to find the issue :)
}
}
You can initialize your path variables as global variables at the top of your class, then just modify them within your requestImage method.
Then when you want to retrieve those images, you can just use the same variable name to ensure that it is the exact same path.
EDIT*
I think you may need to be reading some NSData instead. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to write your file to the documents directory. I found a tutorial here

Why are deleted files coming back after a new write to file? Swift 2.0

I am writing an app in swift that logs sensor data to a txt file. When I have an event occur that needs to be logged I create the filename
func createNewLogFile (){
// Create a new file name
currentFileName = "log\(NSDate()).txt"
//get the path
let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
//create the file
_ = paths[0].URLByAppendingPathComponent(currentFileName)
}
After the file is created I write data to the new file like this:
func writeData (data: String){
// get the path to document directory
let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let filePath = paths[0].URLByAppendingPathComponent(currentFileName)
//get the data to be logged
let stringLocation = data
let stringData = stringLocation.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
//look to see if the file exist
if NSFileManager.defaultManager().fileExistsAtPath(filePath.path!) {
do {
//seek to the end of the file to append data
let fileHandle = try NSFileHandle(forWritingToURL: filePath)
fileHandle.seekToEndOfFile()
fileHandle.writeData(stringData)
fileHandle.closeFile()
} catch {
print("Can't open fileHandle \(error)")
}
} else {
do {
// write to new file
try stringData.writeToURL(filePath, options: .DataWritingAtomic)
} catch {
print("Can't write to new file \(error)")
}
}
}
When I delete the files (from a different ViewController or the same, I tried both)
I am calling this DeleteAllFiles
func deleteAllFiles (Extension: String){
let dirs = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let dir = dirs[0]
do {
let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(dir, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
//return fileList as [String]
for elements in fileList{
do{
try NSFileManager.defaultManager().removeItemAtURL(elements)
print("old Files has been removed")
} catch let error as NSError {
print(error.localizedDescription)
}
}
}catch let error as NSError {
print(error.localizedDescription)
}
}
I then refresh the list and the files seem to be gone.(even when I go back and forth between views) However, when I write a new file and refresh the list the files are back with the new file.
This even happens when I delete them from iTunes using the shared files feature.
Any ideas on why this is happening? I am not getting any helpful error messages.
I found the fix for the problem.
When I was creating the file I actually only meant to create the file name. There was no reason to actually create the file at this time. I am creating the actual file when I write to it.
func createNewLogFile (){
// Create a new file name
currentFileName = "log\(NSDate()).txt"
//Removed creating actual file code
}

Having trouble saving a file in a folder inside Document directory in Swift 2

I am trying to save a file inside a subfolder in Documents directory but it won't save. I can't seem to find what's wrong. Here is what I've tried:
if let audioUrl = NSURL(string: "http://pillar.foundationu.com/wp-content/plugins/pillar-data-sync/php/htmlBreakdownResult.json") {
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
do {
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
print(directoryContents[0].path!)
if NSFileManager().fileExistsAtPath(String(audioUrl.path!)) {
print("The file already exists at path")
} else {
// if the file doesn't exist
// just download the data from your url
if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
// after downloading your data you need to save it to your destination url
if myAudioDataFromUrl.writeToURL(NSURL(fileURLWithPath: directoryContents[0].path!), atomically: true) {
print("file saved")
} else {
print("error saving file")
}
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
Here is where I want to save the file:
/Users/rendell/Library/Developer/CoreSimulator/Devices/5A052CC5-FD34-44FD-B060-24D6F1970860/data/Containers/Data/Application/37753B0B-FAB0-478D-A7F8-98E3039D07DD/Documents/MyFolder2
But it keeps on giving me "error saving file".
First of all, use always writeToURL:options:error to get a (more) descriptive error message.
The issue is quite simple: You forgot to provide a file name.
Technically you're going to overwrite an existing folder with data. That's not possible.

Resources