Create a txt file - swift : IOS

fr0zt

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related