Swift. Can`t save file to DocumentDirectory. Whats wrong? - swift2

Here`s my code:
let fileName = "someFileName"
func saveDataToFile(urlStr:String){
let url = NSURL(string: urlStr)
var data:NSData!
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName
let fileManager = NSFileManager.defaultManager()
data = NSData(contentsOfURL: url!)
print(data) // prints a lot of data
if data != nil{
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
}
}
Now I want to read this data:
func readDataFromFile(){
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath) // prints the same path
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath){
data = fileManager.contentsAtPath(filePath)
}else{
print("*****BAD*****") // always prints this which means that file wasn`t created
}
}
What`s wrong with the first func? What is the right way to save file to DocumentDirectory?

OK, in this case the answer was following:
First need to create directory (aka folder) and only after that create file inside that directory.
Added to code this:
let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)
do{
try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
print(error.localizedDescription)
}
And as I said after this you create your file:
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
Thanks to Eric.D
Hope someone will find this useful.

Related

Is there a way of producing a playground app?

Xcode newbie.(me.dumb)
First time poster.
I have the following code and it tested flawlessly in Xcode Playground(h/t D.Budd Data Science).
I want to turn the code into a MacOS app and I cannot fathom the correct Project and Settings
to do this or do I need to import the Playground into a Project and modify it?
Also this app needs to run in the background (ie, no Window/UI) as this would destroy the current window scene(MagicMirror), sort of like an Automater app can do. It would have an app icon, of course.
Thanks so much for any help.
import Cocoa
extension String{
// get the file name from string
func fileName() -> String{
return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
}
// get the file extension from a string
func fileExtension() -> String{
return URL(fileURLWithPath: self).pathExtension
}
}
func readFile(inputFile: String) -> String{
//split the file extension and file name
let fileExtension = inputFile.fileExtension()
let fileName = inputFile.fileName()
//get the file URL
let fileURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let inputFile = fileURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension)
//get the data
do{
let saveData = try String(contentsOf: inputFile)
return saveData
} catch {
return error.localizedDescription
}
}
func writeFile(outputFile: String, stringData: String){
let fileExtension = outputFile.fileExtension()
let fileName = outputFile.fileName()
//get the fileURL
let fileURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let outputFile = fileURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension)
//save the data
guard let data = stringData.data(using: .utf8) else {
print("No Can Do")
return
}
do {
try data.write(to: outputFile)
print("data written: /data")
} catch {
print(error .localizedDescription)
}
let myData = readFile(inputFile: "test.txt")
writeFile(outputFile: "output.txt", stringData: myData)
}

Array of files from directory

I have the following code working on playground, and I get the array at imageURLs.
let imagePath = str
let url = NSURL(fileURLWithPath: imagePath)
let fileManager = FileManager.default
let properties = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
let imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
Then I add "do" "catch" to handle the errors on the project but it stops working.
let imagePath = Gal.urlDirectorio
let url = NSURL(fileURLWithPath: imagePath)
let fileManager = FileManager.default
let properties = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
do { imageURLs = try fileManager.contentsOfDirectory(at: url as URL, includingPropertiesForKeys: properties, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
} catch {
}
I follow the debugging process and everthing works until the "do" line. I have no error but it doesn't add the urls to the array.

Move Document/Inbox file to another location - Xcode 7, Swift 2

I have a file that is in my Documents/Inbox and is shown in my Print log:
File:
file:///private/var/mobile/Containers/Data/Application/5388031B-48B5-48D6-8299-B3FEDC1D7F45/Documents/Inbox/Pizza-6.pdf
I looked here and saw a way to delete files, but I want to move them out of the Inbox folder to another folder I want to create. How would I do this? I can't find anything for iOS and Swift 2. Thank you.
Here is what I ended up doing:
// MOVING AND SAVING INCOMING PDF TO FILE MANAGER FROM INBOX
let filemgr = NSFileManager.defaultManager()
let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// Create a new folder in the directory named "Recipes"
print("Creating new folder...")
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let newPath = documentsPath.URLByAppendingPathComponent("Recipes")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(newPath.path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
// Then check if the Recipes directory exists. If not, create it
let recipesURL = docsDirURL.URLByAppendingPathComponent("Recipes")
if !filemgr.fileExistsAtPath(docsDirURL.path!) {
do {
try filemgr.createDirectoryAtURL(recipesURL, withIntermediateDirectories: true, attributes: nil)
print("Directory created at: \(recipesURL)")
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
return
}
}
// Move file from Inbox to Recipes Folder
let incomingFileName = incomingFileTransfer.lastPathComponent!
let startingURL = incomingFileTransfer
let savePDFURL = recipesURL.URLByAppendingPathComponent(incomingFileName)
if !filemgr.fileExistsAtPath(savePDFURL.path!) {
do {
try filemgr.moveItemAtURL(startingURL, toURL: savePDFURL)
} catch let error as NSError {
NSLog("Unable to move file \(error.debugDescription)")
}
}

how to create a text file in swift 2

I wonder how I can create a .txt file in a folder in Application Support. How can I do?
let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(/*how to create a text file in Application Support > some folder?*/)
// create a folder in Application Support
var path = String()
let applicationSupportDirectory = NSSearchPathDirectory.ApplicationSupportDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains( applicationSupportDirectory, nsUserDomainMask, true )
let fileManager = NSFileManager.defaultManager()
path = paths[0] + "/" + folderNameYouWant
// check if the folder already exists
if fileManager.fileExistsAtPath( path ) == false
{
_ = try? fileManager.createDirectoryAtPath( path,
withIntermediateDirectories: true,
attributes: nil )
}
// prepare content and write to file
let content = "text file content"
_ = try? content.writeToFile( path,
atomically: true,
encoding: NSUTF8StringEncoding )

Cocoa/Swift: Loop through names of folder in path

I'm currently programming an os x application with swift, but I can't figure how to loop through or even get the names of all folders at a certain path. Maybe something with fm.enumeratorAtPath?
I use enumeratorAtURL. Here's some code that shows an example of how to print the directories in the user's home directory.
if let dirURL = NSURL(fileURLWithPath: NSHomeDirectory()) {
let keys = [NSURLIsDirectoryKey, NSURLLocalizedNameKey]
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(
dirURL,
includingPropertiesForKeys: keys,
options: (NSDirectoryEnumerationOptions.SkipsPackageDescendants |
NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants |
NSDirectoryEnumerationOptions.SkipsHiddenFiles),
errorHandler: {(url, error) -> Bool in
return true
}
)
while let element = enumerator?.nextObject() as? NSURL {
var getter: AnyObject?
element.getResourceValue(&getter, forKey: NSURLIsDirectoryKey, error: nil)
let isDirectory = getter! as Bool
element.getResourceValue(&getter, forKey: NSURLLocalizedNameKey, error: nil)
let itemName = getter! as String
if isDirectory {
println("\(itemName) is a directory in \(dirURL.absoluteString)")
//do something with element here.
}
}
}

Resources