Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a text file with NSURL in Swift

Tags:

macos

swift

nsurl

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

like image 402
Romain Avatar asked Nov 07 '14 09:11

Romain


People also ask

How to read&write to a text file in Swift?

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!

What is nsurlsession in Swift?

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.

What is nsurlsession in iOS 7 and later?

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

What is nsurlconnection in iOS 7?

“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.


1 Answers

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
like image 156
Anthony Kong Avatar answered Sep 23 '22 01:09

Anthony Kong