write a string variable to a file

How do I write a string variable to a text file? I don't know how to read the declaration shown in this documentation (https://developer.apple.com/documentation/swift/string/1641490-write).


func write<Target>(to target: inout Target) where Target : TextOutputStream


Using the context help that fills in your code when you type, I came up with the following, but it gets an error saying that "atomically" is an extra argument I don't need.


            recipientsString.write(toFile: Bundle.main.path(forResource: "recipientsWithProviders", ofType: "txt"), atomically: true, encoding: .utf8)

Is it IOS ?


Test with this

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/recipientsWithProviders.txt"

    do {
        try recipientsString.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
    } catch _ {
    }
}

Mayn look here for further details

h ttps://stackoverflow.com/questions/5619719/write-a-file-on-ios


You could also use archiver

        let paths = NSSearchPathForDirectoriesInDomains(
            FileManager.SearchPathDirectory.documentDirectory,
            FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentsDirectory = paths[0] as NSString  /
        let filePath = documentsDirectory.appendingPathComponent("recipientsWithProviders.txt") as String

        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(recipientsString, forKey: "TextKey")
        archiver.finishEncoding()
        data.write(toFile: filePath, atomically: true)

As I mentioned, String.write(toFile:_:_:) is no longer supported. It has been replaced with String.write(to:), which writes to TextOutputStream.


I tried the second option with the following code:


        let recipientsString = "Diverti, Antonio;(phone number);AT&T\n"
      
        let filePath = Bundle.main.path(forResource: "recipientsWithProviders", ofType: "txt")!
      
        let data = NSMutableData()
      
        let archiver = NSKeyedArchiver(forWritingWith: data)
      
        archiver.encode(recipientsString, forKey: "TextKey")
        archiver.finishEncoding()
        data.write(toFile: filePath, atomically: true)


The filePath is the path to the file I included in my Xcode project. The code went smoothly, but the file recipientsWithProviders.txt was still empty at the end.

Is it Swift 3 or Swift 4 ?


I cannot be totally sure for Swift 4, but in Swift 3 it works.

But it's on NSData, not on String.

So you need to convert.

let data = recipientsString.data(using: .utf8)
    do {
        try data.write(toFile: Bundle.main.path(forResource: "recipientsWithProviders", ofType: "txt")!, atomically: false, encoding: String.Encoding.utf8)
    } catch _ {
    }
}

it throws, so you need to use try.


Reference : h ttps://developer.apple.com/documentation/foundation/nsdata/1414800-write

func write(toFile path: NSData.WritingOptions = []) throws

It seems I got it to work except that the file is in my Xcode project. I think it's not working because the file I am accessing is in my Xcode project. I think I'll just print it to the debug window and then cut and past the information into the file in my Xcode project. Thanks for the help.

Accepted Answer

A couple of things:


— Your app cannot write to or otherwise modify its own bundle. Your write operation failed.


— Don't use any file-handling API that doesn't throw an error upon failure. Any existing API that does not should be regarded as obsolete, even if not officially deprecated.


— As far as possible, avoid file-handling API that takes a path parameter. It is recommended to use the variant that takes a URL. If a path-based method doesn't have a URL-based equivalent, you should regard it as obsolete, even if not officially deprecated.


— You've apparently gone off in the wrong direction anyway. If you're trying to create a text file, archiving a String variable won't give you the desired result. (An archive is a binary file that needs to be decoded to extract its contents.)


— You really need to get into the habit of checking the documentation (in Xcode or at developer.apple.com) before choosing API, especially when there are multiple similar choices available. Picking the wrong one accidentally really slows the development process down.


The correct approach is to convert the String to a Data instance, using the encoding that you want in your text file (such as UTF-8). Then use the Data method "write(to:options:)" to write the data to the file. (Using a URL to specify a location where you app can legally write a file, of course.)


Claude, it's really confusing if you continue to suggest Swift 3 syntax, since there are lots of changes in Swift 4. Even if you continue to use an earlier Xcode for your own projects, you should really install Xcode 9 (or, preferably Xcode 9.1 or whatever is latest) for trying out code fragments you post. (Xcode 9 can co-exist with earlier Xcodes on your Mac, though can't run 9 and earlier versions simultaneously.)

write a string variable to a file
 
 
Q