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.
Here is my code:
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))
})
I tried to do it with NSString.stringWithContentsOfURL but it seems to be deprecated on OS X 10.10.
The text file located at on the server has only one line (UTF8).
Any clue? Thanks
Did you call 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