0

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
}
fr0zt
  • 733
  • 4
  • 12
  • 30

1 Answers1

1

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

enter image description here

Satheesh
  • 10,998
  • 6
  • 50
  • 93