我想阅读并显示位于URL的文本文件的内容.我正在为优胜美地编写Mac应用程序,我需要使用Swift,但我坚持这一点.
这是我的代码:
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))
})
Run Code Online (Sandbox Code Playgroud)
我尝试使用NSString.stringWithContentsOfURL来做,但它似乎在OS X 10.10上已被弃用.
位于服务器上的文本文件只有一行(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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4817 次 |
| 最近记录: |