简体   繁体   English

Swift:writeToFile不保存iOS设备上的文件

[英]Swift: writeToFile does not save file on iOS device

I have a string I read from a text file: text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)! 我有一个从文本文件中读取的字符串: text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)! . Using println(text) I get the output "some text". 使用println(text)我得到输出“some text”。

Now I also have another string otherSting = "other text" . 现在我还有另一个字符串otherSting = "other text" What I want to do is save this text to the text file. 我想要做的是将此文本保存到文本文件中。 I tried using otherText.writeToFile(path!, atomically: true, encoding: NSUTF8StringEncoding, error: nil) and then reading the text file again. 我尝试使用otherText.writeToFile(path!, atomically: true, encoding: NSUTF8StringEncoding, error: nil)然后再次读取文本文件。 When trying on the iOS Simulator I get the output I expected: "other text". 在尝试iOS模拟器时,我得到了我期望的输出:“其他文本”。 But when executing the same app on my iPhone i still get "some text". 但是当我在iPhone上执行相同的应用程序时,我仍然会得到“一些文字”。 Does anybody know what I am doing wrong? 有谁知道我做错了什么?

Edit: 编辑:

I also tried using otherText.writeToURL(url!, atomically: true, encoding: NSUTF8StringEncoding, error: nil) with the same results. 我也尝试使用otherText.writeToURL(url!, atomically: true, encoding: NSUTF8StringEncoding, error: nil) ,结果相同。

Thanks in advance 提前致谢

If you get the old text, you are clearly reading the old file. 如果您收到旧文本,则表明您正在阅读旧文件。 Make sure you have two different path or url variables. 确保您有两个不同的pathurl变量。

What happened most likely is that you saved to file1, tried to overwrite that same file1 which failed silently, so that file1 contains the original data. 最有可能发生的事情是你保存到file1,试图覆盖默认失败的同一个文件1,以便file1包含原始数据。

Also, as Paulw has pointed out, you cannot write to your bundle. 另外,正如Paulw指出的那样,你不能写信给你的包。 Instead you have to copy files to the application documents directory first, or create them there. 相反,您必须先将文件复制到应用程序文档目录 ,或在那里创建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM