0
Data Files management on Swift !!
How create, open, write and update a txt file, using Swift programming language ?
1 Antwort
0
The swift programminng language uses URLs for File IO, which may be confusing to many begginers. To keep it short, you need to get the URL of your file, then you will be able to convert the URL to Data and then Decode, Print, or whatever you want to do. For example, You may have a “data.txt” file inside your project. To get the URL of your file you will need to use the Bundle.main.url(forResource:,withExtension:) initialiser. This URL will be optional so to safely unwrap it, we will be using an “if let” conditional. Then to get the Data, you will need to use the Data(contentsOf:) which is again an optional initialiser, init?(). So, the code to print out the contents of “data.txt” would look like this: “””
import Foundation
if let url = Bundle.main.url(forResource: "data", withExtension: "txt") {
if let fileContent = try? Data(contentsOf: url) {
print(String(data: fileContent, encoding: .utf8) ?? "")
}
}
“”” If you need any additional help, I’m happy to help. Pawel