Swift writing log file in yosemite - swift

I have a program that writes string to a file. It works perfectly in macos mojave but not in yosemite.
Using Xcode 11 and Swift 5
The code is
(Log.swift)
import Foundation
open class Log {
open var maxFileSize: UInt64 = 102400
open var maxFileCount = 365
///The directory in which the log files will be written
open var directory = Log.defaultDirectory() {
didSet {
directory = NSString(string: directory).expandingTildeInPath
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: directory) {
do {
try fileManager.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: nil)
} catch {
NSLog("Couldn't create directory at \(directory)")
}
}
}
}
open var currentPath: String {
return "\(directory)/\(logName(0))"
}
///The name of the log files
open var name = "logfile"
///Whether or not logging also prints to the console
open var printToConsole = true
///logging singleton
open class var logger: Log {
struct Static {
static let instance: Log = Log()
}
return Static.instance
}
//the date formatter
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .medium
return formatter
}
///write content to the current log file.
open func write(_ text: String) {
let path = currentPath
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
do {
try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
} catch _ {
}
}
if let fileHandle = FileHandle(forWritingAtPath: path) {
let dateStr = dateFormatter.string(from: Date())
let writeText = "[\(dateStr)]: \(text)\n"
fileHandle.seekToEndOfFile()
fileHandle.write(writeText.data(using: String.Encoding.utf8)!)
fileHandle.closeFile()
}
}
///Recursive method call to rename log files
func rename(_ index: Int) {
let fileManager = FileManager.default
let path = "\(directory)/\(logName(index))"
let newPath = "\(directory)/\(logName(index+1))"
if fileManager.fileExists(atPath: newPath) {
rename(index+1)
}
do {
try fileManager.moveItem(atPath: path, toPath: newPath)
} catch _ {
}
}
///gets the log name
func logName(_ num :Int) -> String {
return "\(name)-\(num).log"
}
///get the default log directory
class func defaultDirectory() -> String {
var path = ""
let fileManager = FileManager.default
let urls = fileManager.urls(for: .libraryDirectory, in: .userDomainMask)
//let urls = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
if let url = urls.last {
path = "\(url.path)/TestingLog/Logs"
}
if !fileManager.fileExists(atPath: path) && path != "" {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
} catch _ {
}
}
return path
}
}
///Writes content to the current log file
public func logw(_ text: String) {
Log.logger.write(text)
}
In another swift file I use logw("test1") to print test1 in a file in applicationsupport directory.
Whats wrong that makes it not write in yosemite?
I need it to not delete the file or the text inside the file and make it keep appending it when writing the log.

i can see from the code above in your
open func write(_ text: String) {
let path = currentPath
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
do {
try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
} catch _ {
}
}
}
method the string value passed to log is not used anywhere. . Can you please clarify this

Related

How To Read From File Swift [duplicate]

I need to read and write data to/from a text file, but I haven't been able to figure out how.
I found this sample code in the Swift's iBook, but I still don't know how to write or read data.
import Cocoa
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a non-trivial amount of time to initialize.
*/
var fileName = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
#lazy var importer = DataImporter()
var data = String[]()
// the DataManager class would provide data management functionality here
}
let manager = DataManager()
manager.data += "Some data"
manager.data += "Some more data"
// the DataImporter instance for the importer property has not yet been created”
println(manager.importer.fileName)
// the DataImporter instance for the importer property has now been created
// prints "data.txt”
var str = "Hello World in Swift Language."
For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.
Swift 3.x - 5.x
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}
Swift 2.2
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}
Swift 1.x
let file = "file.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"
//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}
Assuming that you have moved your text file data.txt to your Xcode-project (Use drag'n'drop and check "Copy files if necessary") you can do the following just like in Objective-C:
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let content = NSString.stringWithContentsOfFile(path) as String
println(content) // prints the content of data.txt
Update:
For reading a file from Bundle (iOS) you can use:
let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)
Update for Swift 3:
let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
For Swift 5
let path = Bundle.main.path(forResource: "ListAlertJson", ofType: "txt") // file path for file "data.txt"
let string = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
Xcode 8.x • Swift 3.x or later
do {
// get the documents folder url
if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
// create the destination url for the text file to be saved
let fileURL = documentDirectory.appendingPathComponent("file.txt")
// define the string/text to be saved
let text = "Hello World !!!"
// writing to disk
// Note: if you set atomically to true it will overwrite the file if it exists without a warning
try text.write(to: fileURL, atomically: false, encoding: .utf8)
print("saving was successful")
// any posterior code goes here
// reading from disk
let savedText = try String(contentsOf: fileURL)
print("savedText:", savedText) // "Hello World !!!\n"
}
} catch {
print("error:", error)
}
New simpler and recommended method:
Apple recommends using URLs for filehandling and the other solutions here seem deprecated (see comments below).
The following is the new simple way of reading and writing with URL's:
Swift 5+, 4 and 3.1
import Foundation // Needed for those pasting into Playground
let fileName = "Test"
let dir = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask, appropriateFor: nil, create: true)
guard let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") else {
fatalError("Not able to create URL")
}
// Writing to the file named Test
let outString = "Write this text to the file"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
assertionFailure("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
// Reading it back from the file
var inString = ""
do {
inString = try String(contentsOf: fileURL)
} catch {
assertionFailure("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("Read from the file: \(inString)")
Xcode 8, Swift 3 way to read file from the app bundle:
if let path = Bundle.main.path(forResource: filename, ofType: nil) {
do {
let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(text)
} catch {
printError("Failed to read text from \(filename)")
}
} else {
printError("Failed to load file from app bundle \(filename)")
}
Here's a convenient copy and paste Extension
public extension String {
func contentsOrBlank()->String {
if let path = Bundle.main.path(forResource:self , ofType: nil) {
do {
let text = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
return text
} catch { print("Failed to read text from bundle file \(self)") }
} else { print("Failed to load file from bundle \(self)") }
return ""
}
}
For example
let t = "yourFile.txt".contentsOrBlank()
You almost always want an array of lines:
let r:[String] = "yourFile.txt"
.contentsOrBlank()
.characters
.split(separator: "\n", omittingEmptySubsequences:ignore)
.map(String.init)
I want to show you only the first part, that is read. Here's how simply you can read:
Swift 3:
let s = try String(contentsOfFile: Bundle.main.path(forResource: "myFile", ofType: "txt")!)
Swift 2:
let s = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("myFile", ofType: "txt")!)
Simplest way to read a file in Swift > 4.0
let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
do {
var text = try String(contentsOfFile: path!)
}
catch(_){print("error")}
}
You may find this tool useful to not only read from file in Swift but also parse your input: https://github.com/shoumikhin/StreamScanner
Just specify the file path and data delimiters like this:
import StreamScanner
if let input = NSFileHandle(forReadingAtPath: "/file/path")
{
let scanner = StreamScanner(source: input, delimiters: NSCharacterSet(charactersInString: ":\n")) //separate data by colons and newlines
while let field: String = scanner.read()
{
//use field
}
}
Hope, this helps.
This works with Swift 3.1.1 on Linux:
import Foundation
let s = try! String(contentsOfFile: "yo", encoding: .utf8)
The current accepted answer above from Adam had some errors for me but here is how I reworked his answer and made this work for me.
let file = "file.txt"
let dirs: [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if (dirs != nil) {
let directories:[String] = dirs!
let dirs = directories[0]; //documents directory
let path = dirs.stringByAppendingPathComponent(file);
let text = "some text"
//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
//reading
var error:NSError?
//reading
let text2 = String(contentsOfFile: path, encoding:NSUTF8StringEncoding, error: &error)
if let theError = error {
print("\(theError.localizedDescription)")
}
}
To avoid confusion and add ease, I have created two functions for reading and writing strings to files in the documents directory. Here are the functions:
func writeToDocumentsFile(fileName:String,value:String) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
let path = documentsPath.stringByAppendingPathComponent(fileName)
var error:NSError?
value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error)
}
func readFromDocumentsFile(fileName:String) -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
let path = documentsPath.stringByAppendingPathComponent(fileName)
var checkValidation = NSFileManager.defaultManager()
var error:NSError?
var file:String
if checkValidation.fileExistsAtPath(path) {
file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String
} else {
file = "*ERROR* \(fileName) does not exist."
}
return file
}
Here is an example of their use:
writeToDocumentsFile("MyText.txt","Hello world!")
let value = readFromDocumentsFile("MyText.txt")
println(value) //Would output 'Hello world!'
let otherValue = readFromDocumentsFile("SomeText.txt")
println(otherValue) //Would output '*ERROR* SomeText.txt does not exist.'
Hope this helps!
Xcode Version: 6.3.2
I had to recode like this:
let path = NSBundle.mainBundle().pathForResource("Output_5", ofType: "xml")
let text = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding)
print(text)
In the function example, (read|write)DocumentsFromFile(...) having some function wrappers certainly seems to makes sense since everything in OSx and iOS seems to need three or four major classes instantiated and a bunch of properties, configured, linked, instantiated, and set, just to write "Hi" to a file, in 182 countries.
However, these examples aren't complete enough to use in a real program. The write function does not report any errors creating or writing to the file. On the read, I don't think it's a good idea to return an error that the file doesn't exist as the string that is supposed to contain the data that was read. You would want to know that it failed and why, through some notification mechanism, like an exception. Then, you can write some code that outputs what the problem is and allows the user to correct it, or "correctly" breaks the program at that point.
You would not want to just return a string with an "Error file does not exist" in it. Then, you would have to look for the error in the string from calling function each time and handle it there. You also possibly couldn't really tell if the error string was actually read from an actual file, or if it was produced from your code.
You can't even call the read like this in swift 2.2 and Xcode 7.3 because NSString(contentsOfFile...) throws an exception. It is a compile time error if you do not have any code to catch it and do something with it, like print it to stdout, or better, an error popup window, or stderr. I have heard that Apple is moving away from try catch and exceptions, but it's going to be a long move and it's not possible to write code without this. I don't know where the &error argument comes from, perhaps an older version, but NSString.writeTo[File|URL] does not currently have an NSError argument. They are defined like this in NSString.h :
public func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws
public convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws
Also, the file not existing is just one of a number of potential problems your program might have reading a file, such as a permissions problem, the file size, or numerous other issues that you would not even want to try to code a handler for each one of them. It's best to just assume it's all correct and catch and print, or handle, an exception if something goes amiss, besides, at this point, you don't really have a choice anyway.
Here are my rewrites :
func writeToDocumentsFile(fileName:String,value:String) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString!
let path = documentsPath.stringByAppendingPathComponent(fileName)
do {
try value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
print("ERROR : writing to file \(path) : \(error.localizedDescription)")
}
}
func readFromDocumentsFile(fileName:String) -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let path = documentsPath.stringByAppendingPathComponent(fileName)
var readText : String = ""
do {
try readText = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
}
catch let error as NSError {
print("ERROR : reading from file \(fileName) : \(error.localizedDescription)")
}
return readText
}
For my txt file works this way:
let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)
print(String(myText))
Latest swift3 code
You can read data from text file just use bellow code
This my text file
{
"NumberOfSlices": "8",
"NrScenes": "5",
"Scenes": [{
"dataType": "label1",
"image":"http://is3.mzstatic.com/image/thumb/Purple19/v4/6e/81/31/6e8131cf-2092-3cd3-534c-28e129897ca9/mzl.syvaewyp.png/53x53bb-85.png",
"value": "Hello",
"color": "(UIColor.red)"
}, {
"dataType": "label2",
"image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
"value": "Hi There",
"color": "(UIColor.blue)"
}, {
"dataType": "label3",
"image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
"value": "hi how r u ",
"color": "(UIColor.green)"
}, {
"dataType": "label4",
"image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
"value": "what are u doing ",
"color": "(UIColor.purple)"
}, {
"dataType": "label5",
"image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
"value": "how many times ",
"color": "(UIColor.white)"
}, {
"dataType": "label6",
"image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/5a/f3/06/5af306b0-7cac-1808-f440-bab7a0d18ec0/mzl.towjvmpm.png/53x53bb-85.png",
"value": "hi how r u ",
"color": "(UIColor.blue)"
}, {
"dataType": "label7",
"image":"http://is5.mzstatic.com/image/thumb/Purple71/v4/a8/dc/eb/a8dceb29-6daf-ca0f-d037-df9f34cdc476/mzl.ukhhsxik.png/53x53bb-85.png",
"value": "hi how r u ",
"color": "(UIColor.gry)"
}, {
"dataType": "label8",
"image":"http://is2.mzstatic.com/image/thumb/Purple71/v4/15/23/e0/1523e03c-fff2-291e-80a7-73f35d45c7e5/mzl.zejcvahm.png/53x53bb-85.png",
"value": "hi how r u ",
"color": "(UIColor.brown)"
}]
}
You can use this code you get data from text json file in swift3
let filePath = Bundle.main.path(forResource: "nameoftheyourjsonTextfile", ofType: "json")
let contentData = FileManager.default.contents(atPath: filePath!)
let content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String
print(content)
let json = try! JSONSerialization.jsonObject(with: contentData!) as! NSDictionary
print(json)
let app = json.object(forKey: "Scenes") as! NSArray!
let _ : NSDictionary
for dict in app! {
let colorNam = (dict as AnyObject).object(forKey: "color") as! String
print("colors are \(colorNam)")
// let colour = UIColor(hexString: colorNam) {
// colorsArray.append(colour.cgColor)
// colorsArray.append(colorNam as! UIColor)
let value = (dict as AnyObject).object(forKey: "value") as! String
print("the values are \(value)")
valuesArray.append(value)
let images = (dict as AnyObject).object(forKey: "image") as! String
let url = URL(string: images as String)
let data = try? Data(contentsOf: url!)
print(data)
let image1 = UIImage(data: data!)! as UIImage
imagesArray.append(image1)
print(image1)
}
It is recommended to read and write files asynchronously! and it's so easy to do in pure Swift,
here is the protocol:
protocol FileRepository {
func read(from path: String) throws -> String
func readAsync(from path: String, completion: #escaping (Result<String, Error>) -> Void)
func write(_ string: String, to path: String) throws
func writeAsync(_ string: String, to path: String, completion: #escaping (Result<Void, Error>) -> Void)
}
As you can see it allows you to read and write files synchronously or asynchronously.
Here is my implementation in Swift 5:
class DefaultFileRepository {
// MARK: Properties
let queue: DispatchQueue = .global()
let fileManager: FileManager = .default
lazy var baseURL: URL = {
try! fileManager
.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("MyFiles")
}()
// MARK: Private functions
private func doRead(from path: String) throws -> String {
let url = baseURL.appendingPathComponent(path)
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: url.path, isDirectory: &isDir) && !isDir.boolValue else {
throw ReadWriteError.doesNotExist
}
let string: String
do {
string = try String(contentsOf: url)
} catch {
throw ReadWriteError.readFailed(error)
}
return string
}
private func doWrite(_ string: String, to path: String) throws {
let url = baseURL.appendingPathComponent(path)
let folderURL = url.deletingLastPathComponent()
var isFolderDir: ObjCBool = false
if fileManager.fileExists(atPath: folderURL.path, isDirectory: &isFolderDir) {
if !isFolderDir.boolValue {
throw ReadWriteError.canNotCreateFolder
}
} else {
do {
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
} catch {
throw ReadWriteError.canNotCreateFolder
}
}
var isDir: ObjCBool = false
guard !fileManager.fileExists(atPath: url.path, isDirectory: &isDir) || !isDir.boolValue else {
throw ReadWriteError.canNotCreateFile
}
guard let data = string.data(using: .utf8) else {
throw ReadWriteError.encodingFailed
}
do {
try data.write(to: url)
} catch {
throw ReadWriteError.writeFailed(error)
}
}
}
extension DefaultFileRepository: FileRepository {
func read(from path: String) throws -> String {
try queue.sync { try self.doRead(from: path) }
}
func readAsync(from path: String, completion: #escaping (Result<String, Error>) -> Void) {
queue.async {
do {
let result = try self.doRead(from: path)
completion(.success(result))
} catch {
completion(.failure(error))
}
}
}
func write(_ string: String, to path: String) throws {
try queue.sync { try self.doWrite(string, to: path) }
}
func writeAsync(_ string: String, to path: String, completion: #escaping (Result<Void, Error>) -> Void) {
queue.async {
do {
try self.doWrite(string, to: path)
completion(.success(Void()))
} catch {
completion(.failure(error))
}
}
}
}
enum ReadWriteError: LocalizedError {
// MARK: Cases
case doesNotExist
case readFailed(Error)
case canNotCreateFolder
case canNotCreateFile
case encodingFailed
case writeFailed(Error)
}
write in ViewDidLoad
var error: NSError?
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var documentsDirectory = paths.first as String
var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")
if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
} else {
println("not creted or exist")
}
func listDocumentDirectoryfiles() -> [String] {
if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder")
return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String]
}
return []
}
func writeToDocumentsFile(fileName:String,value:String) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let path = documentsPath.appendingPathComponent(fileName)
do{
try value.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
}catch{
}
}
func readFromDocumentsFile(fileName:String) -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let path = documentsPath.appendingPathComponent(fileName)
let checkValidation = FileManager.default
var file:String
if checkValidation.fileExists(atPath: path) {
do{
try file = NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
}catch{
file = ""
}
} else {
file = ""
}
return file
}
Earlier solutions answers question, but in my case deleting old content of file while writing was a problem.
So, I created piece of code for writing to file in documents directory without deleting previous content. You probably need better error handling, but I believe it's good starting point. Swift 4.
Usuage:
let filename = "test.txt"
createOrOverwriteEmptyFileInDocuments(filename: filename)
if let handle = getHandleForFileInDocuments(filename: filename) {
writeString(string: "aaa", fileHandle: handle)
writeString(string: "bbb", fileHandle: handle)
writeString(string: "\n", fileHandle: handle)
writeString(string: "ccc", fileHandle: handle)
}
Helper methods:
func createOrOverwriteEmptyFileInDocuments(filename: String){
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
debugPrint("ERROR IN createOrOverwriteEmptyFileInDocuments")
return
}
let fileURL = dir.appendingPathComponent(filename)
do {
try "".write(to: fileURL, atomically: true, encoding: .utf8)
}
catch {
debugPrint("ERROR WRITING STRING: " + error.localizedDescription)
}
debugPrint("FILE CREATED: " + fileURL.absoluteString)
}
private func writeString(string: String, fileHandle: FileHandle){
let data = string.data(using: String.Encoding.utf8)
guard let dataU = data else {
debugPrint("ERROR WRITING STRING: " + string)
return
}
fileHandle.seekToEndOfFile()
fileHandle.write(dataU)
}
private func getHandleForFileInDocuments(filename: String)->FileHandle?{
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
debugPrint("ERROR OPENING FILE")
return nil
}
let fileURL = dir.appendingPathComponent(filename)
do {
let fileHandle: FileHandle? = try FileHandle(forWritingTo: fileURL)
return fileHandle
}
catch {
debugPrint("ERROR OPENING FILE: " + error.localizedDescription)
return nil
}
}
Swift 3.x - 5.x
The Best Example is to Create a Local Logfile with an Extension .txt
that can visible and show in the "Files App" with current date and Time as a File Name
just add this code in info.plist enable these two features
UIFileSharingEnabled
LSSupportsOpeningDocumentsInPlace
and this Function Below
var logfileName : String = ""
func getTodayString() -> String{
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let second = components.second
let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) + "-" + String(hour!) + "" + String(minute!) + "" + String(second!)+".txt"
return today_string
}
func LogCreator(){
logfileName = getTodayString()
print("LogCreator: Logfile Generated Named: \(logfileName)")
let file = logfileName //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0]
print("LogCreator: The Logs are Stored at location \(documentPath)")
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
print("LogCreator: The Detail log are :-\(text2)")
}
catch {/* error handling here */}
}
}
[1]: https://i.stack.imgur.com/4eg12.png
Xcode 8.3.2 Swift 3.x. Using NSKeyedArchiver and NSKeyedUnarchiver
Reading file from documents
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json")
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {
let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any]
}
else{
print("File does not exists")
}
Write file to documents
NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)

Could not open obj file

so I'm working on a project that pulls zip files which include .obj files, unzips them and displays them using ARkit. At the moment I've been able to unzip and save the file in my documents directory as a .obj file and it says the file exists, but when I try to convert it into a scn it says "Could not open OBJ file". Here is my code and I'm trying to figure out where I went wrong. The file size is 314 KB so I know that's not the issue and the obj file isn't corrupted because I can download it to my computer and open it up.
class ViewController: UIViewController {
var testData: Store?
var logoImage: UIImage?
var urlForObject: String?
var tempDirectoryString: String?
var tempDirectoryURL: URL?
var testModelData: Data?
var testData2: Data?
var testData3: Models?
var tempDocumentsURL: URL?
#IBOutlet weak var logoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.clearCowZipFolder()
self.clearCowFolder()
self.requestZipFile(){ response in
self.testData2 = response
do{
let json = try? JSONSerialization.jsonObject(with: response, options: [])
if let array = json as? [String] {
if let firstObject = array.first {
//print(firstObject)
}
for object in array {
// access all objects in array
}
for case let string as String in array {
// access only string values in array
}
}
}catch{
print("errorrrr")
}
}
self.tempDocumentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = self.tempDocumentsURL!.appendingPathComponent("Man.zip")
var destPath = self.tempDocumentsURL!.appendingPathComponent("Man")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://markitapi.com/stores/TestStore/models/Man")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response3, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response3 as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
do{
let unzipDirectory = try Zip.quickUnzipFile(destinationFileUrl) //Unzip
print("HHERHERHEHRE")
destPath = unzipDirectory
}catch{
print("error while unzipping")
}
print("UNZIPPED PATH")
//print(destPath)
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("Man/Man.obj") {
let filePath = pathComponent.path
//print(filePath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} else {
print("FILE PATH NOT AVAILABLE")
}
let url2 = (String(describing: destPath) + "Man.obj")
let url3 = URL(fileURLWithPath: url2)
print(url3.pathExtension)
let asset = MDLAsset(url: url3)
//print(asset)
let object = asset.object(at: 0)
let node = SCNNode(mdlObject: object)
//print(node)
}
} else {
//print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task.resume()
}
func clearCowZipFolder() {
let fileNameToDelete = "Man.zip"
var filePath = ""
// Fine documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
//print("Local path = \(filePath)")
} else {
print("Could not find local directory to store file")
return
}
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: filePath) {
// Delete file
try fileManager.removeItem(atPath: filePath)
} else {
print("File does not exist")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
}
func clearCowFolder() {
let fileNameToDelete = "Man"
var filePath = ""
// Fine documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
//print("Local path = \(filePath)")
} else {
print("Could not find local directory to store file")
return
}
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: filePath) {
// Delete file
try fileManager.removeItem(atPath: filePath)
} else {
print("File does not exist")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
}
func requestZipFile(success successBlock: #escaping (Data) -> Void){
Alamofire.request("http://markitapi.com/stores/TestStore/models").responseJSON { (response) in
do{
if(response.result.isSuccess){
successBlock(response.data!)
}
}catch{
print("error")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The first part of the code checks to see if the file is available and it does print that statement, so I know the file is there.

Swift 3: Reading content of folder? [duplicate]

What is wrong with my code for getting the filenames in the document folder?
func listFilesFromDocumentsFolder() -> [NSString]?{
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0] as NSString
let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as [NSString]
return fileList
}else{
return nil
}
}
I thought I read the documents correctly and I am very sure about what is in the documents folder, but "fileList" does not show anything? "dir" shows the path to the folder.
Swift 5
do {
// Get the document directory url
let documentDirectory = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
print("documentDirectory", documentDirectory.path)
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(
at: documentDirectory,
includingPropertiesForKeys: nil
)
print("directoryContents:", directoryContents.map { $0.localizedName ?? $0.lastPathComponent })
for url in directoryContents {
print(url.localizedName ?? url.lastPathComponent)
}
// if you would like to hide the file extension
for var url in directoryContents {
url.hasHiddenExtension = true
}
for url in directoryContents {
print(url.localizedName ?? url.lastPathComponent)
}
// if you want to get all mp3 files located at the documents directory:
let mp3s = directoryContents.filter(\.isMP3).map { $0.localizedName ?? $0.lastPathComponent }
print("mp3s:", mp3s)
} catch {
print(error)
}
You would need to add those extensions to your project
extension URL {
var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
var isMP3: Bool { typeIdentifier == "public.mp3" }
var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
var hasHiddenExtension: Bool {
get { (try? resourceValues(forKeys: [.hasHiddenExtensionKey]))?.hasHiddenExtension == true }
set {
var resourceValues = URLResourceValues()
resourceValues.hasHiddenExtension = newValue
try? setResourceValues(resourceValues)
}
}
}
This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:
import Foundation
extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}
// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")
A shorter syntax for SWIFT 3
func listFilesFromDocumentsFolder() -> [String]?
{
let fileMngr = FileManager.default;
// Full path to documents directory
let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path
// List all contents of directory and return as [String] OR nil if failed
return try? fileMngr.contentsOfDirectory(atPath:docs)
}
Usage example:
override func viewDidLoad()
{
print(listFilesFromDocumentsFolder())
}
Tested on xCode 8.2.3 for iPhone 7 with iOS 10.2 & iPad with iOS 9.3
Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:):
You should consider using the FileManager methods urls(for:in:) and url(for:in:appropriateFor:create:) which return URLs, which are the preferred format.
With Swift 5, FileManager has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:). contentsOfDirectory(at:includingPropertiesForKeys:options:) has the following declaration:
Performs a shallow search of the specified directory and returns URLs for the contained items.
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager's urls(for:in:) and contentsOfDirectory(at:includingPropertiesForKeys:options:) methods:
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
As an example, the UIViewController implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:
import UIKit
class ViewController: UIViewController {
#IBAction func copyFile(_ sender: UIButton) {
// Get file url
guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
print("Copy item succeeded")
} catch {
print("Could not copy file: \(error)")
}
}
}
#IBAction func displayUrls(_ sender: UIButton) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
}
}
Simple and dynamic solution (Swift 5):
extension FileManager {
class func directoryUrl() -> URL? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths.first
}
class func allRecordedData() -> [URL]? {
if let documentsUrl = FileManager.directoryUrl() {
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
return directoryContents.filter{ $0.pathExtension == "m4a" }
} catch {
return nil
}
}
return nil
}}
This code prints out all the directories and files in my documents directory:
Some modification of your function:
func listFilesFromDocumentsFolder() -> [String]
{
let dirs = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs != [] {
let dir = dirs[0]
let fileList = try! FileManager.default.contentsOfDirectory(atPath: dir)
return fileList
}else{
let fileList = [""]
return fileList
}
}
Which gets called by:
let fileManager:FileManager = FileManager.default
let fileList = listFilesFromDocumentsFolder()
let count = fileList.count
for i in 0..<count
{
if fileManager.fileExists(atPath: fileList[i]) != true
{
print("File is \(fileList[i])")
}
}
Swift 2.0 Compability
func listWithFilter () {
let fileManager = NSFileManager.defaultManager()
// We need just to get the documents folder url
let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
do {
// if you want to filter the directory contents you can do like this:
if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
print(directoryUrls)
........
}
}
}
OR
func listFiles() -> [String] {
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0]
do {
let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
return fileList as [String]
}catch {
}
}else{
let fileList = [""]
return fileList
}
let fileList = [""]
return fileList
}

Documents folder working in Simulator but not iPad - Swift 2.1

The below code unzips a folder of images into a folder I create. and then loops through it and adds the names to an array, then loops through this array and retrieves those file names into an array of images.
It works perfectly on the simulator, but the data is empty when I do it on the iPad, it prints out nothing. I can only assume the folder isn't accessible or is being searched before the unzip has completed, but It shouldnt as I am using NSOperationQueue with a completion block.
func unzipData(objectData: NSManagedObject) {
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDir = paths[0]
let zipPath = documentsDir.stringByAppendingString("MyZipFiles")
let folderPath = documentsDir.stringByAppendingString("/docLibFiles") // My folder name in document directory
var optData = NSData(data: objectData.valueForKey("image") as! NSData)
print(objectData.valueForKey("imageUrl") as! String)
optData.writeToFile(zipPath, atomically: true)
let success = fileManager.fileExistsAtPath(zipPath) as Bool
if success == false {
do {
try! fileManager.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil)
}
}
queue.addOperationWithBlock { () -> Void in
let operation1 = NSBlockOperation(block: {
let unZipped = SSZipArchive.unzipFileAtPath(zipPath, toDestination: folderPath)
})
operation1.completionBlock = {
dispatch_async(dispatch_get_main_queue(), {
if queue.operationCount == 0 {
self.retrieveFiles()
}
})
}
queue.addOperation(operation1)
}
}
func getDocumentsURL() -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
return documentsURL
}
func fileInDocumentsDirectory(filename: String) -> String {
let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!
}
func retrieveFiles() {
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDir = paths[0]
let zipPath = documentsDir.stringByAppendingString("MyZipFiles")
let folderPath = documentsDir.stringByAppendingString("/docLibFiles") // My folder name in document directory
do {
let filelist = try fileManager.contentsOfDirectoryAtPath(folderPath)
print(filelist)
print("filename")
for filename in filelist {
fileNameArray.append(filename)
}
} catch let error as NSError {
print("Could not save \(error)")
}
do {
for item in fileNameArray {
print("item \(item)")
let imagePath = fileInDocumentsDirectory("docLibFiles/\(item)")
imageArray.append(UIImage(contentsOfFile: imagePath)!)
}
print("filename array \(fileNameArray)")
print("image array \(imageArray)")
unzipDelegate!.unzipSet(imageArray)
}
}
In case of avoiding an error is generated by some trivial typos. Probably process paths in NSURL form
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDir = paths[0]
let url = NSURL(fileURLWithPath: documentsDir)
url.URLByAppendingPathComponent("MyZipFiles")
url.URLByAppendingPathComponent("docLibFiles")
Im not exactly sure why the initial problem was there, but my code was definitely overcomplicated. Ive sorted it now, hopefully it will help someone else in swift 2.1
class UnzipDocument {
let queue = NSOperationQueue() // BACKGROUND THREAD
var imageArray = [UIImage]()
var fileNameArray = [String]()
var fileManager = NSFileManager.defaultManager()
let compressedFile = NSTemporaryDirectory().stringByAppendingString("MyZipFiles")
let uncompressedFolder = NSTemporaryDirectory().stringByAppendingString("MyUnzippedFiles")
func unzipData(objectData: NSManagedObject){ // THIS IS BASICALLY NSDATA FROM CORE DATA FOR ME
let optData = NSData(data: objectData.valueForKey("image") as! NSData)
let success = fileManager.fileExistsAtPath(uncompressedFolder) as Bool // CREATES THE FOLDER IF IT DOESNT EXIST
if success == false {
do {
try! fileManager.createDirectoryAtPath(uncompressedFolder, withIntermediateDirectories: true, attributes: nil)
}
}
optData.writeToFile(compressedFile, atomically: true)
queue.addOperationWithBlock { () -> Void in
let operation1 = NSBlockOperation(block: {
SSZipArchive.unzipFileAtPath(self.compressedFile, toDestination: self.uncompressedFolder)
})
operation1.completionBlock = {
if queue.operationCount == 0 {
dispatch_async(dispatch_get_main_queue(), {
if queue.operationCount == 0 {
self.retrieveFiles()
}
})
}
}
queue.addOperation(operation1)
}
}
func retrieveFiles() {
do {
let filelist = try fileManager.contentsOfDirectoryAtPath(uncompressedFolder)
print(filelist)
print("filename")
for filename in filelist {
self.fileNameArray.append(filename)
}
} catch let error as NSError {
print("Could not save \(error)")
}
do {
for item in fileNameArray {
print("item \(item)")
let imagePath = uncompressedFolder.stringByAppendingString("/\(item)")
imageArray.append(UIImage(contentsOfFile: imagePath)!)
}
print("filename array \(fileNameArray)")
print("image array \(imageArray)")
unzipDelegate!.unzipSet(imageArray)
} catch {
}
}
}
and to delete the temp file/folder after use, so that it can be reused without any old documents remaining
var fileManager = NSFileManager.defaultManager()
let compressedFile = NSTemporaryDirectory().stringByAppendingString("MyZipFiles")
let uncompressedFolder = NSTemporaryDirectory().stringByAppendingString("MyUnzippedFiles")
do {
try fileManager.removeItemAtPath(compressedFile)
try fileManager.removeItemAtPath(uncompressedFolder)
} catch let error as NSError {
print("Could not save \(error)")
}

Append text or data to text file in Swift

I already have read Read and write data from text file
I need to append the data (a string) to the end of my text file.
One obvious way to do it is to read the file from disk and append the string to the end of it and write it back, but it is not efficient, especially if you are dealing with large files and doing in often.
So the question is "How to append string to the end of a text file, without reading the file and writing the whole thing back"?
so far I have:
let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
let fileurl = dir.URLByAppendingPathComponent("log.txt")
var err:NSError?
// until we find a way to append stuff to files
if let current_content_of_file = NSString(contentsOfURL: fileurl, encoding: NSUTF8StringEncoding, error: &err) {
"\(current_content_of_file)\n\(NSDate()) -> \(object)".writeToURL(fileurl, atomically: true, encoding: NSUTF8StringEncoding, error: &err)
}else {
"\(NSDate()) -> \(object)".writeToURL(fileurl, atomically: true, encoding: NSUTF8StringEncoding, error: &err)
}
if err != nil{
println("CANNOT LOG: \(err)")
}
Here's an update for PointZeroTwo's answer in Swift 3.0, with one quick note - in the playground testing using a simple filepath works, but in my actual app I needed to build the URL using .documentDirectory (or which ever directory you chose to use for reading and writing - make sure it's consistent throughout your app):
extension String {
func appendLineToURL(fileURL: URL) throws {
try (self + "\n").appendToURL(fileURL: fileURL)
}
func appendToURL(fileURL: URL) throws {
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
extension Data {
func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else {
try write(to: fileURL, options: .atomic)
}
}
}
//test
do {
let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
let url = dir.appendingPathComponent("logFile.txt")
try "Test \(Date())".appendLineToURL(fileURL: url as URL)
let result = try String(contentsOf: url as URL, encoding: String.Encoding.utf8)
}
catch {
print("Could not write to file")
}
Thanks PointZeroTwo.
You should use NSFileHandle, it can seek to the end of the file
let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
let fileurl = dir.URLByAppendingPathComponent("log.txt")
let string = "\(NSDate())\n"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
var err:NSError?
if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &err) {
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
}
else {
println("Can't open fileHandle \(err)")
}
}
else {
var err:NSError?
if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &err) {
println("Can't write \(err)")
}
}
A variation over some of the posted answers, with following characteristics:
based on Swift 5
accessible as a static function
appends new entries to the end of the file, if it exists
creates the file, if it doesn't exist
no cast to NS objects (more Swiftly)
fails silently if the text cannot be encoded or the path does not exist
class Logger {
static var logFile: URL? {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let dateString = formatter.string(from: Date())
let fileName = "\(dateString).log"
return documentsDirectory.appendingPathComponent(fileName)
}
static func log(_ message: String) {
guard let logFile = logFile else {
return
}
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let timestamp = formatter.string(from: Date())
guard let data = (timestamp + ": " + message + "\n").data(using: String.Encoding.utf8) else { return }
if FileManager.default.fileExists(atPath: logFile.path) {
if let fileHandle = try? FileHandle(forWritingTo: logFile) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
}
} else {
try? data.write(to: logFile, options: .atomicWrite)
}
}
}
Here is a way to update a file in a much more efficient way.
let monkeyLine = "\nAdding a 🐵 to the end of the file via FileHandle"
if let fileUpdater = try? FileHandle(forUpdating: newFileUrl) {
// Function which when called will cause all updates to start from end of the file
fileUpdater.seekToEndOfFile()
// Which lets the caller move editing to any position within the file by supplying an offset
fileUpdater.write(monkeyLine.data(using: .utf8)!)
// Once we convert our new content to data and write it, we close the file and that’s it!
fileUpdater.closeFile()
}
Here's a version for Swift 2, using extension methods on String and NSData.
//: Playground - noun: a place where people can play
import UIKit
extension String {
func appendLineToURL(fileURL: NSURL) throws {
try self.stringByAppendingString("\n").appendToURL(fileURL)
}
func appendToURL(fileURL: NSURL) throws {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
try data.appendToURL(fileURL)
}
}
extension NSData {
func appendToURL(fileURL: NSURL) throws {
if let fileHandle = try? NSFileHandle(forWritingToURL: fileURL) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.writeData(self)
}
else {
try writeToURL(fileURL, options: .DataWritingAtomic)
}
}
}
// Test
do {
let url = NSURL(fileURLWithPath: "test.log")
try "Test \(NSDate())".appendLineToURL(url)
let result = try String(contentsOfURL: url)
}
catch {
print("Could not write to file")
}
In order to stay in the spirit of #PointZero Two.
Here an update of his code for Swift 4.1
extension String {
func appendLine(to url: URL) throws {
try self.appending("\n").append(to: url)
}
func append(to url: URL) throws {
let data = self.data(using: String.Encoding.utf8)
try data?.append(to: url)
}
}
extension Data {
func append(to url: URL) throws {
if let fileHandle = try? FileHandle(forWritingTo: url) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
} else {
try write(to: url)
}
}
}
Update: I wrote a blog post on this, which you can find here!
Keeping things Swifty, here is an example using a FileWriter protocol with default implementation (Swift 4.1 at the time of this writing):
To use this, have your entity (class, struct, enum) conform to this protocol and call the write function (fyi, it throws!).
Writes to the document directory.
Will append to the text file if the file exists.
Will create a new file if the text file doesn't exist.
Note: this is only for text. You could do something similar to write/append Data.
import Foundation
enum FileWriteError: Error {
case directoryDoesntExist
case convertToDataIssue
}
protocol FileWriter {
var fileName: String { get }
func write(_ text: String) throws
}
extension FileWriter {
var fileName: String { return "File.txt" }
func write(_ text: String) throws {
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
throw FileWriteError.directoryDoesntExist
}
let encoding = String.Encoding.utf8
guard let data = text.data(using: encoding) else {
throw FileWriteError.convertToDataIssue
}
let fileUrl = dir.appendingPathComponent(fileName)
if let fileHandle = FileHandle(forWritingAtPath: fileUrl.path) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
} else {
try text.write(to: fileUrl, atomically: false, encoding: encoding)
}
}
}
All answers (as of now) recreate the FileHandle for every write operation. This may be fine for most applications, but this is also rather inefficient: A syscall is made, and the filesystem is accessed each time you create the FileHandle.
To avoid creating the filehandle multiple times, use something like:
final class FileHandleBuffer {
let fileHandle: FileHandle
let size: Int
private var buffer: Data
init(fileHandle: FileHandle, size: Int = 1024 * 1024) {
self.fileHandle = fileHandle
self.size = size
self.buffer = Data(capacity: size)
}
deinit { try! flush() }
func flush() throws {
try fileHandle.write(contentsOf: buffer)
buffer = Data(capacity: size)
}
func write(_ data: Data) throws {
buffer.append(data)
if buffer.count > size {
try flush()
}
}
}
// USAGE
// Create the file if it does not yet exist
FileManager.default.createFile(atPath: fileURL.path, contents: nil)
let fileHandle = try FileHandle(forWritingTo: fileURL)
// Seek will make sure to not overwrite the existing content
// Skip the seek to overwrite the file
try fileHandle.seekToEnd()
let buffer = FileHandleBuffer(fileHandle: fileHandle)
for i in 0..<count {
let data = getData() // Your implementation
try buffer.write(data)
print(i)
}