在Swift中使用NSURL读取文本文件 [英] Read a text file with NSURL in Swift
本文介绍了在Swift中使用NSURL读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想阅读并显示位于URL的文本文件的内容. 我正在为优胜美地编写Mac App,我需要使用Swift,但是我坚持了这一点.
I want to read and display the content of a text file that is located at an URL. I am coding a Mac App for Yosemite and I need to use Swift but I stuck on this.
这是我的代码:
let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
println((urlContents))
})
我尝试使用NSString.stringWithContentsOfURL进行此操作,但似乎在OS X 10.10上已弃用.
I tried to do it with NSString.stringWithContentsOfURL but it seems to be deprecated on OS X 10.10.
位于服务器上的文本文件只有一行(UTF8).
The text file located at on the server has only one line (UTF8).
有任何线索吗?谢谢
推荐答案
您打电话给downloadTask.resume()
吗?
let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!,
completionHandler: {
(location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
println(urlContents)
})
downloadTask.resume() // Call it and you should be able to see the text.txt content
这篇关于在Swift中使用NSURL读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文