This question already has answers here:
Read and write a String from text file
(21 answers)
File write with [NSBundle mainBundle] fails
(5 answers)
Closed 5 years ago.
I got a problem when I was trying to write data into a csv file.
The app reads data from a csv file, and during the application running, the data will change, and when it changes, it will call a function to write the data back to the csv file, but it doesn't work. thanks a lot!!
The code is listed below
var content = ""
if content != ""{
print("have content")
}
for tag in tags{
let line = "\(tag.birdIndex),\(tag.isSeen)\n"
content = content + line
}
if let path = Bundle.main.path(forResource: "birdLogVersion1", ofType: "csv"){
do {
let data = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(data)
}catch{
}
//let url = NSURL(fileURLWithPath: path)
do {
try content.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
//(to: url as URL, atomically: true, encoding: String.Encoding.utf8)
print("tried write")
}catch{
//error
}
}else{
}
when I call this function again, print(data) shows that data has already been written into this csv file, but when I close the app, and restart it again, the csv file still be the same, didn't change at all.
Do I have to do something like save file after write data into a csv file?
Is it right to write info into the csv file in app?
Thanks again!
Related
I am trying to build an app where I am able to access(read/write) windows/mac shared folders in my local network with swift.
Is there any possible way to do that with swift?
There is an App in the App Store called "FileExplorer" https://apps.apple.com/de/app/fe-file-explorer-file-manager/id510282524 where you can access these shared folders, but I do not know how they programmed this and with which language.
I also tried to access my shared folders via this App and yes it worked I can see my shared folders on my Phone.
But there needs to be a way to do it with swift...
I already tried different things(code bellow).
In the code bellow I tried to access the shared folder of my second mac and write the Text "Write this text to the fileURL as text in iOS using Swift" into the file named "Test.txt" and after that I want to read the same file again.
#IBAction func Button(_ sender: UIButton)
{
var uc = URLComponents()
uc.scheme = "smb"
uc.user = "user"
uc.password = "password"
uc.host = "ip-adress"
uc.path = "document-directory"
// Save data to file
let fileName = "Test"
let url = uc.url
//let DocumentDirURL = URL(fileURLWithPath: "/Users/f/d/t/App/Assets/Apps/TestApp")
let DocumentDirURL = try! URL(resolvingAliasFileAt: url!)
let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
// Write to the file
try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
var fullString: String = "" // Used to store the file contents
do {
// Read the file contents
fullString = try String(contentsOf: fileURL, encoding: .utf8)
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")
}
If I run the code as shown, he always gives me the error
"smb scheme is not supported" and then some additional errors that he can not write/read the file because he can not access it.
When I change the code and only search on the device I am programming on and run the simulator to search for this file everything works fine. So I have problems with "smb".
Thank you for every helpful answer.
you can use amsmb2 library to do this
you can extend the template class provided to connect to download files, write files, list directories -> on an smb share
everything is asynchronous from memory, with the librarys calls including hooks for progress updates on the ui main thread etc
i believe the amsmb2 library function your after might be uploadItem
iOS 13 includes SMB (server message block protocol) support
https://9to5mac.com/2019/06/17/ios-13-beta-2-enables-smb-server-connectivity-in-the-files-app/
I'm using this code to save a string to an xml file in my project
let saveTo = statisticsI.toXMLString()
let filepath = Bundle.main.url(forResource: "statistics", withExtension: "xml")
let filepathAlt = Bundle.main.path(forResource: "statistics", ofType: "xml")
print(filepathAlt!)
do {
try saveTo.write(to: filepath!, atomically: false, encoding: String.Encoding.utf8)
let contents = try String(contentsOfFile: filepathAlt!)
print("FILE CONTENTS \(contents)")
}
catch let error as NSError {
print("Error writing values \(error)")
}
Printing the file contents returns the xml correctly, but when I stop running the application, the file hasn't been updated
When the above code is run, the file has already been read by a seperate function. Is the fact that the file has already been accessed (and its path still stored in a variable) the issue?
when I stop running the application, the file hasn't been updated
You can't write into the application bundle in iOS. Try using a path into the Documents folder or some other place within the app's sandbox.
I need help on reading a DOC (.docx or .doc) file's contents and display it inside the UILabel. The file is from the URL, so I download the file to DocumentsDirectory and in the process of finding a solution to read the contents.
I am using Alamofire.download and I have called:
let content = try? String(contentsOfFile: (response.destinationURL?.path)!, encoding: String.Encoding.utf8)
but it is returning nil
Does anyone know how to read the contents of a doc file would be appreciated.
You can use this SNDocx
OR
Doing this is not as easy as you imagine,
a docx file is a zipped up collection of XML and other files. You can't load a docx file into an String. You would need to use Data to load the zip contents. Then you would need to unzip it. Then you would need to go through all of the files and find the desired word/document.xml then read xml and parse .
Im use Zippy
Look this code
guard let originalFileURL = Bundle.main.url(forResource: "test", withExtension: "docx") else {
print("file not found :( ")
return
}
do{
let filename = try! ZipFile.init(url: originalFileURL)
// file name content
// - 0 : "[Content_Types].xml"
// - 1 : "word/numbering.xml"
// - 2 : "_rels/.rels"
// - 3 : "word/theme/theme1.xml"
// - 4 : "word/fontTable.xml"
// - 5 : "word/document.xml"
// - 6 : "word/settings.xml"
// - 7 : "word/styles.xml"
// - 8 : "word/_rels/document.xml.rels"
for file in filename {
if file.contains("document.xml"){
let data = filename[file]
print(String.init(data: data!, encoding: String.Encoding.utf8))
}
}
}catch{
print(error)
}
Output
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r<w:document xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:w10=\"urn:schemas-microsoft-com:office:word\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:wne=\"http://schemas.microsoft.com/office/word/2006/wordml\" xmlns:sl=\"http://schemas.openxmlformats.org/schemaLibrary/2006/main\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:lc=\"http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas\" xmlns:dgm=\"http://schemas.openxmlformats.org/drawingml/2006/diagram\" xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\" xmlns:w15=\"http://schemas.microsoft.com/office/word/2012/wordml\"><w:body><w:p w:rsidR=\"00000000\" w:rsidDel=\"00000000\" w:rsidP=\"00000000\" w:rsidRDefault=\"00000000\" w:rsidRPr=\"00000000\" w14:paraId=\"00000000\"><w:pPr><w:contextualSpacing w:val=\"0\"/><w:rPr/></w:pPr><w:r w:rsidDel=\"00000000\" w:rsidR=\"00000000\" w:rsidRPr=\"00000000\"><w:rPr><w:rtl w:val=\"0\"/></w:rPr><w:t xml:space=\"preserve\">test</w:t></w:r></w:p><w:sectPr><w:pgSz w:h=\"15840\" w:w=\"12240\"/><w:pgMar w:bottom=\"1440\" w:top=\"1440\" w:left=\"1440\" w:right=\"1440\" w:header=\"0\"/><w:pgNumType w:start=\"1\"/></w:sectPr></w:body></w:document>
You have to parse xml this and you will find in the my output that it must be parse until this value is obtained
<w:t xml:space=\"preserve\">test</w:t>
docx XML Format reference
I've some irregular huge amount of data in a text file, and by some crucial logics I've made it just like the way I needs. Now on every time the app loads the whole process if could be performed will cost deficiency up to remarkable extent.
So what should I do in order to store this regular data for one permanent time, so then through that I should retrieve when and where I got need of it?
Data is an unmodifiable pure in text format.
Okay your question is very vague, but to give you a head start you can save data to a file and then read from it like this:
let file = "file.txt" //this is the file we will write to and read from it
let text = "some text" //your data/text
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent(file);
//writing
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {
/* error handling here */
}
//reading
do {
let textOut = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
//use textOut - your content
}
catch {
/* error handling here */
}
}
I've put a "restaurants.txt" file in the same directory with MenuViewController.swift.
Then I put this code in viewDidLoad() of MenuViewController to read the file.
if let path = NSBundle.mainBundle().pathForResource("restaurants", ofType: "txt") {
if let content = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
print(content)
} else {
print("error1")
}
} else {
print("error")
}
Then I get "error1" in my console.
How can I read the file in the same directory of the swift file?
Or do I have to put my "restaurants.txt" file somewhere else?
Add the file to the target:
Select the file
In the Project Navigator command1 select the file icon
Under "Target Membership" click the checkbox for the file.
1) If you wish to read content of a text file, even without inserting it to your project, you may also use NSFileMananger. The following code works, the only drawback - you need to state full path.
let fullPath = "/your/full/path/restaurants.txt"
if NSFileManager.defaultManager().fileExistsAtPath(fullPath){
do
{
let content = try String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding)
print("\(content)")
}
catch let error as NSError
{
print("error reading file: \(error)")
}
}
2) If you do mind the hardcode, and want it more generic - you will have to change Settings in the Build in Xcode. See here:
Locate source project directory in Swift