I am trying to create a txt file in swift language. HOw can i do that?
I tried to check if the file exists:4
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath("history.txt") {
print("File exists")
} else {
print("File not found")
//If the file doesn't exist I want to create it here
}
Could you please try this,
let someDummyTextForTextFile = "Hi there I am the contents of text file"
let data:NSData = someDummyTextForTextFile.dataUsingEncoding(NSUTF8StringEncoding)!
let fileManage = NSFileManager.defaultManager()
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
data.writeToFile("\(dir)/myFile.txt", atomically: true)
}
This will create a text file in your documents directory. Or simply try this,
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
do {
try someDummyTextForTextFile.writeToFile("\(dir)/myFile.txt", atomically: true, encoding: NSUTF8StringEncoding)
}
catch _ {
print("something went wrong")
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments