Click to learn more. Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data. Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into.
That main bundle can be accessed using Bundle. While it might at first seem like Bundle. I am giving an example of storing and retrieving a pdf document in iOS. I hope that is what you are looking for.
Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow.
Learn more. Asked 6 years, 7 months ago. Active 8 months ago. Viewed 73k times. Here are my important questions for that: 1. Improve this question. Jonas Deichelmann 2, 1 1 gold badge 25 25 silver badges 36 36 bronze badges. MkaysWork MkaysWork 1 1 gold badge 7 7 silver badges 11 11 bronze badges. Look at the answer below, there you have the solution ; — MkaysWork. Add a comment.
Active Oldest Votes. DocumentDirectory, inDomains:. Improve this answer. Satre Satre 1, 2 2 gold badges 15 15 silver badges 22 22 bronze badges. I tested your code and it works. I can see the path of the file in the console.
But where is ,in the device, the Documents folder that I see in the path? What if I want to download the file and then display it? Thanks — Ne AS. The first will be content of the text file. The second will be the directory, and the third will be the file name. This method is quite similar to the read method. Add the following method to your code:. We use the append method to add the fileName to the directory , which is just the base path to the Documents directory.
The final part is to write the file. String 's have multiple write methods, we have used the toFile one, which allows us to pass in our filePath as a String. Because writing to the file is not something that can be guaranteed, we need to wrap it in a do try catch , otherwise we will print out the error.
Now that all the methods that we need have been created, we can all them. I am going to call them from viewDidLoad. I have created a let for the fileName because it is used in two places. Then I call the save method which will write "Some test content to write to the file" to a file, and then after the save method I call the read method. All the read method does is print out the contents of the file that we saved. As I mentioned before, I remember writing to files being a pain, but it is actually quick an easy to read and write files.
If you want to look at the final source code, it can be found here. Step 1: Create Documents directory path method I always remember this as being an annoying task, but looking at it now, it really is a simple task.
0コメント