Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift2 快速读取文本文件_Swift2_Xcode7 - Fatal编程技术网

Swift2 快速读取文本文件

Swift2 快速读取文本文件,swift2,xcode7,Swift2,Xcode7,我试图从Swift中的文本文件中读取,但由于某些原因,该文件中的任何内容都无法读取。这是我目前掌握的代码: let location = NSString(string:"/Users/Home/Desktop/file.txt") let fileContent = try? NSString(contentsOfFile: location as String, encoding:NSUTF8StringEncoding) print(fileContent) 这是我文本文件中的内容 li

我试图从Swift中的文本文件中读取,但由于某些原因,该文件中的任何内容都无法读取。这是我目前掌握的代码:

let location = NSString(string:"/Users/Home/Desktop/file.txt")
let fileContent = try? NSString(contentsOfFile: location as String, encoding:NSUTF8StringEncoding)
print(fileContent)
这是我文本文件中的内容

line1
line2
line3
line4
line5

当我在操场上运行这个代码时,它给了我“零”。有人知道原因吗?

您无法从iOS应用程序访问OS X系统文件。模拟器是一个沙盒应用程序。将该文件作为资源包含到Xcode项目中,并通过
NSBundle
访问它:

let location = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")!
let fileContent = try! String(contentsOfURL: location)

您无法从iOS应用程序访问OS X系统文件。模拟器是一个沙盒应用程序。将该文件作为资源包含到Xcode项目中,并通过
NSBundle
访问它:

let location = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")!
let fileContent = try! String(contentsOfURL: location)

嘿@Satish,这对我有用。我假设你的用户名不在家我的用户名不在家。我在操场上运行这个代码。这就是为什么给我“零”的原因吗?我的用户名是詹姆斯。所以我使用了
“/Users/james/Desktop/file.txt”
。您得到的是
nil
,因为您提供的文件路径可能错误。请在终端中键入
whoami
。这将打印您的用户名。然后将您的字符串更改为“
”/Users//Desktop/file.txt”
我的用户名是Satish,所以我的字符串是“/Users/Satish/Desktop/file.txt”,我仍然得到相同的内容嘿@Satish,这对我来说很有用。我假设你的用户名不在家我的用户名不在家。我在操场上运行这个代码。这就是为什么给我“零”的原因吗?我的用户名是詹姆斯。所以我使用了
“/Users/james/Desktop/file.txt”
。您得到的是
nil
,因为您提供的文件路径可能错误。请在终端中键入
whoami
。这将打印您的用户名。然后将您的字符串更改为“
”/Users//Desktop/file.txt”
我的用户名是Satish,所以我的字符串是“/Users/Satish/Desktop/file.txt”,我仍然得到同样的结果