xcode 在 swift 的 iOS 游乐场中读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26538375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:58:46  来源:igfitidea点击:

Read file in swift, iOS playground

iosxcodeswiftswift-playground

提问by alttag

Having searched through the many (many!) swift playground questions to even craft thiscode, I'm still struggling.

在搜索了许多(许多!)swift 操场上的问题来制作这段代码后,我仍然在挣扎。

I've placed a text file in the Resourcesfolder of package contents, and it appears as an alias (link) in the running temp files generated by the playground (/var/folders/ ...).

我在Resources包内容的文件夹中放置了一个文本文件,它在由操场 ( /var/folders/ ...)生成的正在运行的临时文件中显示为别名(链接)。

import UIKit

let bundle = NSBundle.mainBundle()

let myFilePath = bundle.pathForResource("dict1", ofType: "txt")

println(myFilePath)    // <-- this is correct, there is a shortcut to the Resource file at this location

var error:NSError?

var content = String(contentsOfFile:myFilePath!, encoding:NSUTF8StringEncoding, error: &error)

println(content!)  // <-- this is *NOT* the file contents [EDIT: see later note]

// Demonstrate there's no error
if let theError = error {
    print("\(theError.localizedDescription)")
} else {
    print("No error")
}

The problem being, that contentis shown in the playground output as being Some "apple\ngame\nhow\nswift\ntoken", rather than the file contents as expected.

问题是,content在操场输出中显示为 is Some "apple\ngame\nhow\nswift\ntoken",而不是预期的文件内容。

It's finding the file, because if I change the filename, it errors. Any advice on getting the file contents?

它正在查找文件,因为如果我更改文件名,则会出错。关于获取文件内容的任何建议?

Xcode 6.1

Xcode 6.1

EDIT:So, the actualproblem was that I wasn't expecting the playground output (including, println) to be escaped. That, combined with fatigue and other stupidities led me to believe there was a problem, when none existed.

编辑:所以,实际问题是我没想到操场输出(包括,println)会被转义。再加上疲劳和其他愚蠢行为,让我相信存在问题,而实际上根本不存在。

Interestingly, not everything seems to be escaped in playground:

有趣的是,并不是所有的东西似乎都在操场上逃脱了:

println("foo\nbar")    // Outputs "foo\nbar", escaped
println("\n")         // Outputs "\n", unescaped

回答by Leo Dabus

You can try creating a class for opening and saving your files:

您可以尝试创建一个用于打开和保存文件的类:

update: Xcode 10 ? Swift 4.2

更新:Xcode 10?斯威夫特 4.2

class File {
    class func open(_ path: String, encoding: String.Encoding = .utf8) -> String? {
        if FileManager.default.fileExists(atPath: path) {
            do {
                return try String(contentsOfFile: path, encoding: encoding)
            } catch {
                print(error)
                return nil
            }
        }
        return  nil
    }

    class func save(_ path: String, _ content: String, encoding: String.Encoding = .utf8) -> Bool {
        do {
            try content.write(toFile: path, atomically: true, encoding: encoding)
            return true
        } catch {
            print(error)
            return false
        }
    }
}

usage: File.save

用法:File.save

let stringToSave: String = "Your text"

let didSave = File.save("\(NSHomeDirectory())/Desktop/file.txt", stringToSave) 

if didSave { print("file saved") } else { print("error saving file") } 

usage: File.open

用法:File.open

if let loadedData = File.open("\(NSHomeDirectory())/Desktop/file.txt") {
    print(loadedData)
} else {
    println("error reading file")
 }  

If you prefer working with URLs (as I do and recommended by Apple):
Notethat in Swift 4, the class URLalready exists.

如果您更喜欢使用URLs(正如我所做的那样并由 Apple 推荐):
请注意,在 Swift 4 中,该类URL已经存在。

class Url {
    class func open(url: URL) -> String? {
        do {
            return try String(contentsOf: url, encoding: String.Encoding.utf8)
        } catch {
            print(error)
            return nil
        }
    }

    class func save(url: URL, fileContent: String) -> Bool {
        do {
            try fileContent.write(to: url, atomically: true, encoding: .utf8)
            return true
        } catch {
            print(error)
            return false
        }
    }
}

回答by Steve Rosenberg

I have seen this problem with .txt files created from .rtf files using TextEdit.

我已经在使用 TextEdit 从 .rtf 文件创建的 .txt 文件中看到了这个问题。

I loaded a text.txt file in the resources folder of my playground using similar code to you. The file contents was "hello there" and was made by converting an .rtf file to .txt by changing the extension.

我使用与您类似的代码在我的 Playground 的资源文件夹中加载了一个 text.txt 文件。文件内容是“hello there”,是通过更改扩展名将 .rtf 文件转换为 .txt 而成的。

let path = NSBundle.mainBundle().pathForResource("text", ofType: "txt")//or rtf for an rtf file
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)

The output was:

输出是:

{\rtf1\ansi\ansicpg1252\cocoartf1343\cocoasubrtf140 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural

{\rtf1\ansi\ansicpg1252\cocoartf1343\cocoasubrtf140 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margl1440\margl1440\x8view\8view10dview1010 tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural

\f0\fs24 \cf0 hello there}

\f0\fs24 \cf0 你好}

So the "hello there" is embedded. This is the problem with all the layout information in a .rtf file.

所以嵌入了“你好”。这是 .rtf 文件中所有布局信息的问题。

I went back to TextEdit and created a true .txt file. After opening a file - Format|Make Plain Text

我回到 TextEdit 并创建了一个真正的 .txt 文件。打开文件后 - 格式|制作纯文本

Now this same code gave the console output "hello there".

现在,同样的代码给出了控制台输出“hello there”。