Write a File on Ios

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -


and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

How can I write a file in a folder located at Apple's Files App in SwiftUI?

As I have already posted in comments you can NOT programmatically save a file out of your APP Bundle. You can use a UIDocumentInteractionController and ask the user to choose the location where the file is supposed to be written.

So if you are working with SwiftUI this gets a bit more complicated than the regular Storyboard approach as you can see in this post because you need to implement UIViewControllerRepresentable for UIDocumentInteractionController:

struct DocumentInteractionController: UIViewControllerRepresentable {

fileprivate var isExportingDocument: Binding<Bool>
fileprivate let viewController = UIViewController()
fileprivate let documentInteractionController: UIDocumentInteractionController

init(_ isExportingDocument: Binding<Bool>, url: URL) {
self.isExportingDocument = isExportingDocument
documentInteractionController = .init(url: url)

func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentInteractionController>) -> UIViewController { viewController }

func updateUIViewController(_ controller: UIViewController, context: UIViewControllerRepresentableContext<DocumentInteractionController>) {
if isExportingDocument.wrappedValue && documentInteractionController.delegate == nil {
documentInteractionController.uti = documentInteractionController.url?.typeIdentifier ?? "public.data, public.content"
documentInteractionController.name = documentInteractionController.url?.localizedName
documentInteractionController.presentOptionsMenu(from: controller.view.frame, in: controller.view, animated: true)
documentInteractionController.delegate = context.coordinator
documentInteractionController.presentPreview(animated: true)

func makeCoordinator() -> Coordintor { .init(self) }

And its Coordinator:

class Coordintor: NSObject, UIDocumentInteractionControllerDelegate {
let documentInteractionController: DocumentInteractionController
init(_ controller: DocumentInteractionController) {
documentInteractionController = controller
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { documentInteractionController.viewController }

func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) {
controller.delegate = nil
documentInteractionController.isExportingDocument.wrappedValue = false

Now you can create your DocumentInteraction View and its previews:

struct DocumentInteraction: View {
@State private var isExportingDocument = false
var body: some View {
VStack {
Button("Export Document") { self.isExportingDocument = true }
url: Bundle.main.url(forResource: "sample", withExtension: "pdf")!))

struct DocumentInteraction_Previews: PreviewProvider {
static var previews: some View { DocumentInteraction() }

You will need those helpers as well:

extension URL {
var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }

Sample project

How to create a file in an iOS App made with Swift?

Don't use hardcoded paths like "AppData/Documents", instead it's better to ask the system for e.g. the path to the app support directory using

let appSupportDir = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let filePath = appSupportDir.appendingPathComponent("points.txt").path

iOS: How to write to a file at a specific directory in the project?

You cannot write file outside of the application sandbox. Each iOS app have individual directories Document, Library, tmp to store data.

func writeFile(){

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentationDirectory,.userDomainMask,true)
let theFile: FileHandle? = FileHandle(forWritingAtPath: "\(documentsPath)/MyFiles/file.txt")

if theFile != nil { // This is always nil!!!
let data = ("Some text\nline 2\nline3\n" as String).data(using: String.Encoding.utf8)

// Write it to the file

// Close the file
else {
print("Writing failed.")

} // End file writing

An efficient way of writing to file, swift

Probably your bluetooth is reading data faster than you are performing your file operations. You can optimize it by appending the text to the file instead of reading all the content on each write operation. You could also reuse the file handler between writes and keep the file open.

This sample is extracted from this answer:

struct MyStreamer: OutputStreamType {
lazy var fileHandle: NSFileHandle? = {
let fileHandle = NSFileHandle(forWritingAtPath: self.logPath)
return fileHandle

lazy var logPath: String = {
let path : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!
let filePath = (path as NSString).stringByAppendingPathComponent("log.txt")

if !NSFileManager.defaultManager().fileExistsAtPath(filePath) {
NSFileManager.defaultManager().createFileAtPath(filePath, contents: nil, attributes: nil)
return filePath


mutating func write(string: String) {

Then, you can create a single streamer and reuse it in different writes:

var myStream = MyStreamer()
myStream.write("First of all")
myStream.write("Then after")
myStream.write("And, finally")

In this case, you have the bonus that MyStreamer is also a OutputStreamType, so you can use it like this:

var myStream = MyStreamer()
print("First of all", toStream: &myStream )
print("Then after", toStream: &myStream)
print("And, finally", toStream: &myStream)

Finally I'd recommend you to move 'log.txt' string to a instance variable and pass it as a constructor parameter:

var myStream = MyStreamer("log.txt")

More info about file handler in the Apple Docs.

How to read/write file with iOS, in simulator as well as on device?

To read the file from the bundle do the following

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

To read it from your sandbox storage (documents)

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath

To write to document folder

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
[dataFile writeToFile:docPath

Please note you will not be able to write the file in the bundle folder of your application

Write file to documents directory and permissions

No, your app does not need special permissions as such, however scenarios do exist where the app might be unable to write to the file.

One example is if your app is using disk protection for its files, and you try to write to the folder when the disk is encrypted. Other examples are:

  1. The disk is full.
  2. The file is being written to by a different process (ie. you're downloading content to it in a background URLSession).
  3. The path contains some invalid character (e.g. ":").

If an error does occur, the cause can usually be determined by inspecting the error.

The comment seems to be intended a general placeholder indicating some of the possible causes for receiving an error when writing a file, so that if you were to use the code and you ran into an error condition, you would have some place to start.

The documentation is a good place to refer to when in doubt.

Can not write data to file in iOS Swift

Just try to print path of your file in console because you are watching wrong file and check that file if it is available there or not and check content

do {
let string="Amuthapriya"
try string.write(to:fileName, atomically: true, encoding: String.Encoding.utf8)
print("written successfully")
print("filePath: \(filePath)") // check file here
} catch {


Related Topics

Leave a reply