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
Reading & writing to a text file in Swift is simple. We use the documents directory to store our text files and read from them. The code below does this. // Save data to file let fileName = "Test" let DocumentDirURL = try!
Learn NSURLSession using Swift Part 1 - HTTP/HTTPS GET “In iOS7 and later or OS X v10.9 and later, NSURLSession is the preferred API for new code that performs URL requests” — Apple Usually, when an iOS developers wants to retrieve contents from certain URL, they choose to use NSURLConnection.
In iOS 7 and later, Apple suggest to use NSURLSession instead, NSURLSession is just… Swift Programming Sign in Swift Programming Sam Wang Follow Nov 3, 2014·3min read Learn NSURLSession using Swift Part 1 - HTTP/HTTPS GET “In iOS7 and later or OS X v10.9 and later, NSURLSession is the preferred API for new code that performs URL requests” — Apple
“In iOS7 and later or OS X v10.9 and later, NSURLSession is the preferred API for new code that performs URL requests” — Apple Usually, when an iOS developers wants to retrieve contents from certain URL, they choose to use NSURLConnection.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With