在Swift中使用NSURL读取文本文件

Rom*_*ain 8 macos nsurl swift

我想阅读并显示位于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).

任何线索?谢谢

Ant*_*ong 3

你打电话了吗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)