how to create a text file in swift 2 - swift2

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 )

Related

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)")
}
}

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

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.

Get mounted volumes list with Swift?

Does anyone know how to get a list of all removable volumes mounted with Swift?
I've already tried this, but it return a list of all files and subfolders of external drivers:
let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath("/Volumes")
while let file = files?.nextObject() {
println(file)
menu.addItem(NSMenuItem(title: file as! String, action: Selector(""), keyEquivalent: ""))
}
This prints the list of all mounted volumes:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
for url in urls {
println(url)
}
}
You can of course filter to get only the paths inside the "Volumes" directory:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: nil)
if let urls = paths as? [NSURL] {
for url in urls {
if url.relativePath?.pathComponents.count > 1 {
if url.relativePath?.pathComponents[1] == "Volumes" {
println(url)
}
}
}
}
And with Swift 2 there's two differences: pass [] instead of nil for the filemanager's options, and there's no need to cast the array of NSURLs:
let filemanager = NSFileManager()
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = filemanager.mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
for url in urls {
if url.relativePath?.pathComponents.count > 1 {
if url.relativePath?.pathComponents[1] == "Volumes" {
print(url)
}
}
}
}
Update for Swift 2.1
let keys = [NSURLVolumeNameKey, NSURLVolumeIsRemovableKey, NSURLVolumeIsEjectableKey]
let paths = NSFileManager().mountedVolumeURLsIncludingResourceValuesForKeys(keys, options: [])
if let urls = paths {
for url in urls {
if let components = url.pathComponents
where components.count > 1
&& components[1] == "Volumes" {
print(url)
}
}
}
Update for Swift 3
let keys: [URLResourceKey] = [.volumeNameKey, .volumeIsRemovableKey, .volumeIsEjectableKey]
let paths = FileManager().mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [])
if let urls = paths {
for url in urls {
let components = url.pathComponents
if components.count > 1
&& components[1] == "Volumes"
{
print(url)
}
}
}
On Unix systems a filesystem object with a system file number of 2 is a mount, regardless of a remote (nfs, smb, afp) or a local mount.
Here's an example:
let path = "/System/Volumes/Preboot"
let systemAttributes = try FileManager.default.attributesOfItem(atPath: String(describing: path))
if let fileSystemFileNumber = systemAttributes[.systemFileNumber] as? NSNumber {
print("System File Number: \(fileSystemFileNumber)")
}
So maybe this could be a short way to find mounts
let keys: [URLResourceKey] = [
.volumeNameKey,
.volumeIsRemovableKey,
.volumeIsEjectableKey,
.volumeAvailableCapacityKey,
.volumeTotalCapacityKey,
.volumeUUIDStringKey,
.volumeIsBrowsableKey,
.volumeIsLocalKey,
.isVolumeKey,
]
let manager = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys)
if let urls = manager {
print(urls)
}
This code is working fine for MacOS, however on the iOS side it always returns nil. Is there any known workaround?
Thanks!

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.
}
}
}

List files in iTunes shared folder using Swift

I would like to list all files in my iTunes shared folder in a 'Table View' using Swift.
I check on Google and nobody talk about it, it look like it's a uncommon need, so if anyone can help it would be really helpful.
EDIT: I found three links talking about it but in Objective-C, I have no experience in this language. If someone understand this, here are the links.
http://www.exampledb.com/objective-c-get-itunes-file-sharing-folder-files-with-full-path.htm
http://www.infragistics.com/community/blogs/stevez/archive/2013/10/14/ios-objective-c-working-with-files.aspx
http://www.raywenderlich.com/1948/itunes-tutorial-for-ios-how-to-integrate-itunes-file-sharing-with-your-ios-app
Based on this objective-C tutorial http://mobiforge.com/design-development/importing-exporting-documents-ios, I created three methods: listFilesFromDocumentsFolder which returns a list of the names of all documents I have in the apps iTunes shared folder and loadFileFromDocumentsFolder which loads the url for a given filename and passes the url to handleDocumentOpenUrl to load the file on a UIWebView. Find below the three methods.
You can also download the project from github: https://github.com/Euniceadu/Load-Shared-Documents
listFilesFromDocumentsFolder
func listFilesFromDocumentsFolder() {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var fileManager: NSFileManager = NSFileManager()
var fileList: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)!
var filesStr: NSMutableString = NSMutableString(string: "Files in Documents folder \n")
for s in fileList {
filesStr.appendFormat("%#", s as String)
}
self.displayAlert(filesStr)
}
loadFileFromDocumentsFolder
func loadFileFromDocumentsFolder(fileName: String) {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory : String;
documentsDirectory = paths[0] as String
var filePath: String = documentsDirectory.stringByAppendingPathComponent(fileName);
var fileUrl: NSURL = NSURL(fileURLWithPath: filePath);
self.handleDocumentOpenURL(fileUrl)
}
handleDocumentOpenUrl
func handleDocumentOpenURL(url: NSURL) {
var requestObj = NSURLRequest(URL: url)
webView.userInteractionEnabled = true
webView.loadRequest(requestObj)
}
Hope this helps.

Resources